2011-12-16 57 views
1

记录我有以下评论上的模型设计(来源: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被删除)?

+0

它仍然是实际!我想避免明显使用相反的策略 - 清理关联记录时(在连接表中)当通过after_destroy回调删除可评论时。 – 2011-12-23 08:45:35

回答

0

由于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