【问题标题】:Rails, polymorphic association - find records with non-dead associated recordsRails,多态关联 - 查找具有非死关联记录的记录
【发布时间】:2011-12-16 12:02:35
【问题描述】:

我有以下 Comments-on-Models 设计(来源: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...

如何从 'cmets' 表中选择所有记录,以便通过基于范围的查询使每条记录具有非死评论(死意味着原始 fx 帖子已被删除)?

【问题讨论】:

  • 它仍然是真实的!我想避免明显使用相反的策略——当 after_destroy 回调删除可评论时清理关联记录(在连接表中)。
  • 现在不实际,但还是很有趣的!

标签: mysql ruby-on-rails polymorphic-associations


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2011-07-16
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多