user1152706
user1152706

Reputation: 73

rails find all comments where the post's user_id = user

A little bit complicated of a query here. Three relevant tables: users, posts, and comments. The user has_many posts and comments, the posts belong_to the user and has_many comments, and the comments belong_to a user and a post. That said, I'm trying in Rails to, in my controller, find all the comments that a user has received on all his posts. I tried this:

@comments = Comment.where(:post_id.user => @user.id)

But that didn't really work out. This is probably a simple solution, help?

Upvotes: 3

Views: 6625

Answers (2)

Kenny Cason
Kenny Cason

Reputation: 12328

You can also do something like:

@user = User.find(@user.id, :include => :comments)

<% @user.comments.each do |comment| %>
   <%= comment.id %> <br/>
   <%= comment.text %>
<% end %>

Upvotes: 1

Mischa
Mischa

Reputation: 43298

You have to join the posts table for that:

@comments = Comment.joins(:post).where(:posts => { :user_id => @user.id })

Upvotes: 7

Related Questions