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
categories
by caring thehas_many :through
:category_relationships
association (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
categories
by a:position
attribute present incategory_relationships
so that the resultingarticle_categories
are ordered by position; - to eager load also
category_relationship
objects whereuser_id == @current_user.id
since the above code doesn't make that.
How can I make that by taking advantage from the eager loading?