Magnus Skog
Magnus Skog

Reputation: 146

Conditions in "includes" in Activerecord

If I have a model called "Article" and another called "Comment", with each Article having zero or more Comments and each Comment having an associated user, how do I do the following:

Find all articles on the site and any comments that the given user has made

In SQL:

SELECT * FROM articles LEFT OUTER JOIN comments ON articles.id = comments.article_id AND comments.user_id = 2

I have tried doing this:

Article.joins('LEFT OUTER JOIN comments ON articles.id = comments.article_id AND comments.user_id = 2)

The result here is that result.first.comments give me all the comments for the article. I can solve this by adding conditions to the last part, but then it won't be eager

Upvotes: 0

Views: 1154

Answers (2)

Salil
Salil

Reputation: 9722

If you want all the comments made by a particular user and corresponding articles, this should work:

Comment.joins(:articles).where("comments.user_id" => 2).select("comments.*, articles.*")

Upvotes: 2

shime
shime

Reputation: 9008

Can you try with Article.joins(:comments).where("comments.user_id" => 2)?

Look here for more info.

Upvotes: 0

Related Questions