Sad*_*tam 7 ruby-on-rails single-table-inheritance mongoid ruby-1.9.2
我有一个模特
class Post
include Mongoid::Document
include Mongoid::Timestamps
embeds_one :comment
end
Run Code Online (Sandbox Code Playgroud)
我有评论课
class Comment
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :post
field :title
field :description
end
Run Code Online (Sandbox Code Playgroud)
我有另一个继承自评论的类
class RecentComment < Comment
# certain methods
end
Run Code Online (Sandbox Code Playgroud)
现在,我希望能够创建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
Run Code Online (Sandbox Code Playgroud)
并让你的评论类多态
class Comment
include Mongoid::Document
include Mongoid::Timestamps
field :type
validates_inclusion_of :type, :in => ["recent", "other"]
Run Code Online (Sandbox Code Playgroud)