我有一个模特
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
现在我希望能够通过post创建RecentComment如果我做Post.last.build_comment(:_ type =>“RecentComment”)新评论将不是_type:“RecentComment”,同样如果我做Post.last .build_recent_comment,它给我一个错误,就像Post类的未定义方法build_recent_comment一样.如果帖子有references_many:评论我应该做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
并让你的评论类多态
class Comment include Mongoid::Document include Mongoid::Timestamps field :type validates_inclusion_of :type,:in => ["recent","other"]