Jakub Kopyś Jakub Kopyś - 1 year ago 58
Ruby Question

Rails get associations on condition

I have a problem - I do not know how to get associated records only if condition is met.

I have Posts model and Comments, Post

has_many :comments
, Comment
belongs_to :post

Now, I want to retrieve All of the Posts, but only with specific comments (lets say with user_id = 1).
How can I achieve that?
Query like

Post.includes(:comments).where("comments.user_id = ?", "1")
will retrieve only some Posts, I want all of them, but only with comments with user_id equal to 1.

I guess I should use LEFT JOIN of some sort, maybe something like

posts.joins("LEFT JOIN comments ON posts.id comments.post_id")

but I am not sure how to put condition restricting right table results.

Answer Source

It can be achieved as below

Post.includes(:comments).where("comments.user_id = ?", "1").references(:comments)

For more information go here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download