0

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

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

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

之前的 SO question's answers中,听起来我想要某种嵌套的 has_many through。那是对的吗?Rails 3 中是否有任何简单的方法来检测“源”?

4

1 回答 1

1

更新的答案:

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

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在哪里)

于 2012-06-03T22:42:01.113 回答