To put my question in context, I have a form that has many fields. Each field can be at the root or a children of another field (hierarchy using Closure Table in my database). I don't have any problem building the hierarchies table, but I have a problem setting the form_id
on the children fields.
Here is my schema:
create_table "fields", force: :cascade do |t|
t.integer "form_id", null: false
[...]
t.integer "parent_id"
end
And my models (stripped down for simplicity):
class Field < ActiveRecord::Base
has_many :fields,
foreign_key: :parent_id,
inverse_of: :field,
dependent: :destroy
belongs_to :form, inverse_of: :fields, touch: true
belongs_to :field,
foreign_key: :parent_id,
inverse_of: :fields
end
class Form < ActiveRecord::Base
has_many :fields,
inverse_of: :form,
dependent: :destroy
end
If I save my children fields using nested form, I get this error: ERROR: null value in column "form_id" violates not-null constraint
. The form_id
is not passed if I do: Form.find(1).fields.first.fields.new
for example.
Is there a way to set this automatically? The parent_id
is set automatically.
EDIT
Example of the params
stack. I use Trailblazer architecture with Reform.
{
[...]
"fields"=>[{
"id"=>"11",
"_destroy"=>"false",
"position"=>"1",
"value"=>"Foobar",
"fields"=>[{
"id"=>"",
"_destroy"=>"false",
"position"=>"1",
"value"=>"Foobar child"
}]
}]
}