Eager Loading with Conditions
It has been stressed that applying conditions or sorting on an Eager Loading Query may have unintended consequences.
May refer to the following:-
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Eager+loading+of+associations
http://snaprails.tumblr.com/post/234198162/eager-loading
http://stackoverflow.com/questions/9642900/eager-loading-the-right-way-to-do-things
http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations
That is if you have the following,
posts.includes(:comments, :commenters).where("comments.created_at > ?", 1.week.ago)
You probably expect to get all the posts with comments and commenters eager loaded, BUT the comments should be filtered to be all later than 1 week ago.
However, you will find that the result you would get is - all posts with comments that were created more than 1.week.ago, the other posts will not be returned in the result.
You can specify an association with condition in the Post model like so,
has_many :recent_comments, :class_name => "Comment", :conditions => ["created_at > ?", 1.week.ago]