是否可以将活动记录设置为自动限制二级关联



假设我有一个User模型,它has_many :posts,而Post has_many :comments .

如果我这样做@user.posts.map {|post| post.comments}.flatten我会得到用户帖子的所有评论。是否有地方可以配置PostComment模型以检测它是否在特定用户的上下文中被引用并仅返回特定用户的注释?

也就是说,@user.posts.map {|post| post.comments}.flatten@posts.map {|post| post.comments}.flatten(假设相同的帖子)不会返回相同数量的评论(假设多个用户正在评论)。

从前面的 SO 问题的答案来看,听起来我想要某种嵌套has_many。这是对的吗?Rails 3 中是否有任何简单的方法来检测"源"?

更新的答案:

这是一种获取帖子作者评论的方法

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)

最新更新