我经常遇到这种情况
class Post
has_many :comments
end
现在如果我有帖子的关系,我如何获得该帖子的所有评论的关系。
我正在寻找的是
Post.where(user: user).comments
但这不会奏效。我错过了一些明显的东西吗?这似乎是一个常见的用例。
基本上当你Post.where(user: user).includes(:comments)
我们正在预加载所有必需的评论时,我想要的是直接访问它们,而不是Post.where(user: user).includes(:comments).map{|p| p.comments}.flatten.uniq
或类似的东西..
答案 0 :(得分:1)
我定义了一个范围
scope :comments_in_user_posts, -> (user) { where(user: user).includes(:comments).map{|p| p.comments}.flatten }
然后像Post.comments_in_user_posts(user)
一样使用它。
修改强>
另一种选择是使用Comment.where(post: Post.where(user: user))
答案 1 :(得分:1)
您还可以在Post
模型中创建静态方法:
def self.user_comments(user)
Comment.where(post: Post.where(user: user))
end
然后致电:
Post.user_comments(user)
答案 2 :(得分:1)
如果您想获得comment
个对象,请在Comment
课程中实施逻辑。
您可以定义范围,如:
class Comment < ActiveRecord::Base
belongs_to :post
scope :from_user, ->(user_id) { joins(post: :user).where(users: {id: user_id} }
end
这样你就可以打电话了
Comment.from_user(current_user.id)
答案 3 :(得分:-1)
你需要在评论模型中提及,belongs_to:post。
class Comment < ActiveRecord::Base
belongs_to :post
end
现在,当您保存与发布相关的任何评论时。确保@post对象存在。
@post.comments.create(name: "New comment")
您可以尝试在rails控制台中查看内容。现在,当您看到评论对象时。它应该有post_id存在。 所以现在
post_obj.comments
给出一系列评论,comment.post
将给出相关的帖子。