I am running Ruby on Rails 3.1. I would like to eager loading "second degree" associated objects by applying some conditions, but I am in trouble.
It seems that I already solved part of my issue by using:
article_categories =
article
.categories
.includes(:comments => [:category_relationships])
.where(:category_relationships => {:user_id => @current_user.id})
where involved classes are stated as the following:
class Category < ActiveRecord::Base
has_many :comment_relationships
has_many :comments,
:through => :comment_relationships
...
end
class Comment < ActiveRecord::Base
has_many :category_relationships
has_many :categories,
:through => :category_relationships
...
end
The above code (it seems to do it right):
- loads all
categoriesby caring thehas_many :through:category_relationshipsassociation (that is, by caring the.where(:category_relationships => {:user_id => @current_user.id})condition); - eager loads all
article.comments.where(:user_id => @current_user.id).
However, I would like to make some more:
- to order retrieved
categoriesby a:positionattribute present incategory_relationshipsso that the resultingarticle_categoriesare ordered by position; - to eager load also
category_relationshipobjects whereuser_id == @current_user.idsince the above code doesn't make that.
How can I make that by taking advantage from the eager loading?