2

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

Santa
  • 41
  • 6
  • For information, this answer http://stackoverflow.com/questions/4197418/rails-3-eager-loading-with-conditions does'nt help because it doesnt allow dynamic requests. – Santa Oct 04 '12 at 15:10
  • It seems here: https://github.com/rails/rails/issues/4677 that it is simply not possible... It's strange, it seems like a basic standard need. – Santa Oct 05 '12 at 11:22
  • Perhaps this might help? [Stackoverflow: Rails ActiveRecord :joins with LEFT JOIN instead of INNER JOIN](http://stackoverflow.com/questions/1509692/rails-activerecord-joins-with-left-join-instead-of-inner-join) – Raul Pinto Oct 12 '12 at 09:33

0 Answers0