我有一个模型
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
.如果post
有 references_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/