【问题标题】:single table inheritance with embeds_one mogoid带有 embeds_one mogoid 的单表继承
【发布时间】:2011-08-23 06:16:31
【问题描述】:

我有模特

class Post
  include Mongoid::Document
  include Mongoid::Timestamps

  embeds_one :comment
end

我有评论课

class Comment
  include Mongoid::Document
  include Mongoid::Timestamps

  embedded_in :post

  field :title
  field :description
end

我还有另一个类继承自注释

class RecentComment < Comment
  # certain methods
end

现在我希望能够创建RecentCommentpost 如果我这样做Post.last.build_comment(:_type =&gt; "RecentComment") 新评论将不是_type:"RecentComment",同样如果我这样做Post.last.build_recent_comment,它会给我错误提示喜欢undefined method build_recent_comment for Post class。如果postreferences_many :comments 我应该做Post.last.build_comments({}, RecentComment) 没有任何问题。但在这种情况下,我不知道如何使用 RecentComment 类构建对象。如果有人可以提供帮助,那就是 gr8!

注意:我使用的是gem 'mongoid', '~&gt; 2.0.1'

【问题讨论】:

  • 您可能只需要将每种评论类型显式放入 Post 类 - embeds_one :old_comment; embeds_one :new_comment ...
  • 我猜这是创建 Comment 子类的问题之一。拥有子类有什么好处吗?除了名称之外,您可以拥有许多相同的类。如果可能的话,您可能想在变得更难之前立即进行重构。否则,我不确定如何创建您想要的关联,而无需明确地将每个关联都设为嵌入式文档。
  • 但所有派生类都具有与注释相同的字段和属性,因此将它们全部设为不同的嵌入式文档是否合适?
  • 已经很晚了.. 我的所有控制器和方法都使用该关联。也许我问这个问题太晚了。无论如何感谢您的帮助!
  • RecentComment 和常规评论有什么区别?

标签: ruby-on-rails mongoid single-table-inheritance ruby-1.9.2


【解决方案1】:

不妨试试

class Post
  include Mongoid::Document
  include Mongoid::Timestamps

  embeds_one :recent_comment, :class_name => Comment

让你的评论类多态

class Comment
  include Mongoid::Document
  include Mongoid::Timestamps

  field :type
  validates_inclusion_of :type, :in => ["recent", "other"]

【讨论】:

  • 实际上在cmets中还有其他的派生类,比如recentcomment、oldcomment和newcomment。如果只有一个派生类,我相信你的答案会很理想。
【解决方案2】:

一种选择是尝试类似的方法:

class RecentComment < Comment
  store_in "comment"

  #set the type you want
end

但您可能只使用时间戳 以及检索您最近的范围, 旧评论、新评论等,

在评论类中点赞

scope :recent, where("created_at > (Time.now - 1.day)")

那么你可以这样做:

post.comments.recent

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 2011-01-08
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多