我有两个模型Board
和Pictures
,我希望用户能够对Board
整体或个人Pictures
发表评论。
我的多态评论模型:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
然后我在每个其他模型中都有一个简单的has_many
:
class Board < ActiveRecord::Base
has_many :comments, as: :commentable, dependent: :destroy
has_many :pictures
class Pictures < ActiveRecord::Base
has_many :comments, as: :commentable, dependent: :destroy
belongs_to :board
我真正希望能够做的是添加一个名为all_comments
的新范围,它将Board
模型中的注释与Pictures
模型中的相关注释相结合。我可以用一个方法做到这一点,但我最终得到一个数组,而不是一个范围的关系。
我的方法:
def all_comments
comments = self.comments
return comments + self.pictures.map {|x| x.comments}.flatten
end
如何返回可以链接结果的作用域关系?
答案 0 :(得分:4)
首先,图片应该是单一的。
其次,您可以在评论中调用查找器以获取所需的所有评论
Comment.where("type = 'board' AND id IN(?) OR type = 'picture' AND id IN(?)", self.id, self.pictures.map(&:id))
或类似的东西。
答案 1 :(得分:0)
phoet
的回答引起了我的兴趣(我+ 1),所以这是我对他所建议的重构/扩展:
您可以查看Comment
模型以获取相关评论。要做到这一点,你需要首先了解电路板和电路板。与之相关的图片。 Phoet使用self.pictures
对象:
#app/models/comment.rb
Class Board < ActiveRecord::Base
def all_comments
ids = self.id + self.pictures.map(&:id)
Comment.find(ids)
end
end
这将在comment
模型中找到id,将数据作为集合返回。如果你想要真实地表达评论(层次结构),你必须使用某种ancestry
/ inheritance
结构我认为