使用has_many的Mongoid 7.0单表继承

问题描述

我有A类

Company::whereHas('logo',function($query) {
    return $query->where('updated_at','<',Carbon::Now()->subDays(90));
})->orWhereDoesntHave('logo')
->orderBy('name','ASC')
->get();

和B级

class A
    include Mongoid::Document
    has_many :bs
    accepts_nested_attributes_for :bs

和从B继承的类C

class B
    include Mongoid::Document
    belongs_to :a

这与Mongoid 6一起使用效果很好。对于Mongoid 7,在具有fields_for的表单上,提交后,我现在得到:

class C < B
field :new_field,type: String

注意,这不是7.0(我相信)b / c中支持的蒙古式多态性,它不是在谈论单表继承(STI),而是将属于一个类/表的多个表作为同一符号支持。不是那样的而且我尝试使用as和polymorphic:true。

有什么办法解决这个问题吗?

谢谢, 凯文

解决方法

将您转换为Mongoid 7.0或Rails 5.2(不确定是哪个更改导致了此问题),您必须在STI的表单中设置类型,我通过一个隐藏字段来做到这一点:

<%f.hidden_field :_type,value: "C"%>

这使您可以设置仅后代的属性。

,

我遇到了类似的问题。我在一个项目中将 mongoid 从 3.0 升级到 7.0,而 STI 是在旧应用程序中实现的。 _type 在导致意外行为的父表中显式声明。我删除了它,项目开始工作。