ruby-on-rails - 带有 embeds_one mogoid 的单表继承

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

我有一个模型

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

现在我希望能够创建 RecentComment通过 post如果我这样做 Post.last.build_comment(:_type => "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', '~> 2.0.1'

最佳答案

也许试试

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

  embeds_one :recent_comment, :class_name => Comment

并让您的 Comment 类多态
class Comment
  include Mongoid::Document
  include Mongoid::Timestamps

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

关于ruby-on-rails - 带有 embeds_one mogoid 的单表继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963879/

相关文章:

ruby-on-rails - 在 Rails 4 中使用 Devise 实现单表继承

php - 如何在 Doctrine 2 中管理单表继承?

ruby-on-rails - 如何在没有 Active Record 模型的情况下使用 Active Model Serializer?

ruby-on-rails - Rails View 中的变量调用

linux - MongoDB shell 破坏了长查询的语法

mongodb - 如何在 mongoid 5 中创建文本索引?

ruby-on-rails - 渲染 :action and render :template 之间的差异

ruby-on-rails - 在 RSpec 中,消息期望 (receive) 和测试 spy (have_received) 之间有什么区别?

mongodb - 使用 rails 连接 mongodb 中的 2 个表

java - Hibernate,单表继承和使用父类(super class)字段作为鉴别器列