Mongoid 7.0 single table inheritance with has_many

236 Views Asked by At

I have a class A

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

and a class B

class B
    include Mongoid::Document
    belongs_to :a

and a class C that inherits from B

class C < B
field :new_field, type: String

This worked fine with Mongoid 6. With Mongoid 7, on a form with fields_for, upon submit, I now get:

Attempted to set a value for 'new_field' which is not allowed on the model B

Note, this is NOT the mongoid polymorphism supported in 7.0 (I believe) b/c that is not talking about single table inheritance (STI), rather, it supports multiple tables belonging to a single class / table as the same symbol. This is not that. And I've tried using as and polymorphic:true.

Any ideas how to fix this?

Thanks, Kevin

2

There are 2 best solutions below

0
user1130176 On

Turns you for Mongoid 7.0 or Rails 5.2 (not sure which change broke this) you have to set the type in the form for STI, I did this by a hidden field:

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

This allows you to set descendant-only attributes.

0
Saad Abdullah On

I faced a similar sort of issue. I was upgrading mongoid from 3.0 to 7.0 in a project and STI was implemented in the old app. _type was explicitly declared in the parent table which was causing unexpected behavior. I removed it and the project started working.