加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用embeds_one mogoid进行单表继承

发布时间:2020-12-17 04:15:58 所属栏目:百科 来源:网络整理
导读:我有一个模特 class Post include Mongoid::Document include Mongoid::Timestamps embeds_one :commentend 我有评论课 class Comment include Mongoid::Document include Mongoid::Timestamps embedded_in :post field :title field :descriptionend 我还有
我有一个模特
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"]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读