Dirk Bergmann

Developer, panographer. Does consultancy work from own company. Lives in Chiang Mai, Thailand.

Twitter

Chiang Mai

Hua Hin

Thailand Hotels

ListVote - List. Vote. Learn.

Partnerseek - Find Partners

Paginate over HABTM with Globalize2

As outlined in this post, find and paginate require a **:joins => :globalize_translations** statement to eager load the translations.

Here?s an extended version for pagination over a has-and-belongs-to-many (HABTM) relationship:

app/models/widget.rb

has_and_belongs_to_many :categories

?

def self.find_by_category(category_id, page)
      paginate(
      :page => page,
      :per_page => 30,
      #:include => :categories, #does not work but this does:
     ** :joins => [:categories, :globalize_translations],
**      :conditions => ['category_id = ? and locale = ?', category_id, 'en'],
      :order => :name,
      :include => :pictures
     
      )
    end

I couldn?t get  :include => :categories to work, it had to be a :joins => :categories. Coming from the paginated object (in this case Widget) instead of from the related Category lets you eager-load other related models (in this case Pictures) very easily. YMMV.