From Rails documentation http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html:
Post.includes([:author, :comments]).where(['comments.approved = ?', true]).all
Note that using conditions like this can have unintended consequences. In the above example posts with no approved comments are not returned at all, because the conditions apply to the SQL statement as a whole and not just to the association.
Ok, so how to return all posts including the ones with no approved comments in the example ?
I can do it in SQL with:
SELECT posts.* from posts LEFT JOIN comments ON (comments.post_id = posts.id AND comments.approved = true);
But this does'nt work through the joins method of rails because next access to Post.comments will fire an SQL request that will bring all comments approved and not approved.
Any clue ? Thx
Rails 3.2.8