Let’s say I have a User model which has_many :posts, while Post has_many :comments.
If I do @user.posts.map {|post| post.comments}.flatten I’ll get all the comments on the user’s posts. Is there somewhere to configure the Post or Comment model to detect it’s being referenced in the context of a specific user and only return the specific user’s comments?
That is, @user.posts.map {|post| post.comments}.flatten and @posts.map {|post| post.comments}.flatten (assuming the same posts) wouldn’t return the same number of comments (assuming multiple users are commenting).
From a previous SO question’s answers, it sounds like I want some sort of nested has_many through. Is that correct? Is there any easy way in Rails 3 to detect the ‘source’?
Updated answer:
Here’s a method that’ll get a post’s author’s comments
That should let you do:
it’s not as efficient as the other method, though; n posts will result in n SQL queries to get the comments. But it’s pretty close to what was described in the comment below.
Original answer (for posterity)
It ain’t the prettiest, but you can do something like
Call
@user.replies_to_selfto get the users’ comments to his/her own postsYou end up with SQL like this:
(where
Xwould be the user’s id)