[英]How to go from a relation to a relation of associated model in Active Record
我经常遇到这种情况
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
Post.where(user: user).includes(:comments).map{|p| p.comments}.flatten.uniq
或类似的内容。
我会定义一个范围
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))
您还可以在Post
模型中创建静态方法:
def self.user_comments(user)
Comment.where(post: Post.where(user: user))
end
然后致电:
Post.user_comments(user)
如果要获取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)
您需要在注释模型中提到,属居到:post。
class Comment < ActiveRecord::Base
belongs_to :post
end
现在,当您保存与帖子相关的任何评论时。 确保@post对象存在。
@post.comments.create(name: "New comment")
您可以尝试在Rails控制台中检查其中的内容。 现在,当您看到注释对象时。 它应该有post_id存在。 所以现在
post_obj.comments
提供评论数组和comment.post
将提供相关的帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.