Paginate over HABTM with Globalize2

Ruby on Rails Add comments

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.

 

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in