gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:13:16 25 4
gpt4 key购买 nike

我有一个模型

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com