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:


has_and_belongs_to_many :categories


def self.find_by_category(category_id, page)
: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


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.

Posted: 09 February 2009

comments powered by Disqus