更新的答案:
这是一种获取帖子作者评论的方法
class Post < ActiveRecord::Base
belongs_to :user # So, there's a user_id attribute
has_many :comments
def authors_comments
comments.where("user_id = ?", user_id)
end
end
那应该让你这样做:
@user.posts.each { |post| puts post, post.authors_comments }
但是,它不如其他方法有效;n个帖子将导致n 个SQL 查询以获取评论。但这与下面评论中的描述非常接近。
原始答案(为后代)
它不是最漂亮的,但你可以做类似的事情
class User < ActiveRecord::Base
has_many :posts # All the user's posts
has_many :comments # All the user's comments on all posts
# All comments made on any of user's posts
has_many :replies, :through => :posts, :source => :comments
def replies_to_self
replies.where("comments.user_id = ?", id)
end
end
调用@user.replies_to_self
以获取用户对他/她自己的帖子的评论
你最终会得到这样的 SQL:
SELECT
"comments".*
FROM
"comments"
INNER JOIN
"posts"
ON
"comments"."post_id" = "posts"."id"
WHERE
"posts"."user_id" = X AND "comments"."user_id" = X
(X
用户ID在哪里)