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?
您必须加入 posts表:
@comments = Comment.joins(:post).where(:posts => { :user_id => @user.id })
You can also do something like:
@user = User.find(@user.id, :include => :comments)
<% @user.comments.each do |comment| %>
<%= comment.id %> <br/>
<%= comment.text %>
<% end %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.