轨,多态关联 - 发现与非死相关记录
问题描述:
记录我有以下评论上的模型设计(来源: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 Post被删除)?
答
由于commentable
不存在的情况下,死commentable,你可以做这样的事情:
class Comment
belongs_to :commentable, :polymorphic => true
scope :non_dead_commentable, where('commentable IS NOT NULL')
end
在轨道4,你可以这样做:
scope :non_dead_commentable, where.not(:commentable => nil)
然后:
Comment.non_dead_commentable
它仍然是实际!我想避免明显使用相反的策略 - 清理关联记录时(在连接表中)当通过after_destroy回调删除可评论时。 – 2011-12-23 08:45:35