[英]Rails, polymorphic association - find records with non-dead associated records
我有以下基于模型的注释设计(来源: http : //railscasts.com/episodes/154-polymorphic-association ):
class Comment
belongs_to :commentable, :polymorphic => true
end
class Post
has_many :comments, as => :commentable
end
class Message
has_many :comments, :as => :commentable
end
etc...
如何从“评论”表中选择所有记录,以使每个记录都具有基于基于范围的查询的非失效注释(“失效”意味着原始fx帖子已删除)?
由于commentable
不存在,因此commentable
不存在,因此您可以执行以下操作:
class Comment
belongs_to :commentable, :polymorphic => true
scope :non_dead_commentable, where('commentable IS NOT NULL')
end
在rails 4中,您可以执行以下操作:
scope :non_dead_commentable, where.not(:commentable => nil)
接着:
Comment.non_dead_commentable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.