对所有特定用户帖子的所有评论的单一查询是什么?

时间:2015-03-07 01:44:18

标签: ruby-on-rails activerecord

鉴于:用户has_many:发帖为has_many:comments,查询所有用户帖子的所有评论的查询是什么?

jack = User.find(999)

是否只有一个查询可以查找Jack所有帖子的所有评论?

1 个答案:

答案 0 :(得分:1)

class User
  has_many :posts
  has_many :comments
  has_many :received_comments, through: :posts, class_name: 'Comment' 
end

class Post
  belongs_to :user
  has_many :comments
end

class Comment
  belongs_to :post
  belongs_to :user
end 

这使您能够通过用户

查询评论
jack = User.find(999)
jack.received_comments # all comments made on posts belonging to jack
jack.comments # all comments made by jack