0

为了把我的问题放在上下文中,我有一个包含许多字段的表单。每个字段都可以是另一个字段的根或子字段(在我的数据库中使用闭包表的层次结构)。我在构建层次结构表时没有任何问题,但是我form_id在子字段上设置时遇到了问题。

这是我的架构:

create_table "fields", force: :cascade do |t|
    t.integer  "form_id", null: false
    [...]
    t.integer  "parent_id"
end

还有我的模型(为了简单起见):

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

如果我使用嵌套表单保存我的子字段,我会收到此错误:ERROR: null value in column "form_id" violates not-null constraint. 如果我这样做,form_id则不会通过:Form.find(1).fields.first.fields.new例如。

有没有办法自动设置?是自动设置的parent_id

编辑

params堆栈示例。我将 Trailblazer 架构与改革一起使用。

{
    [...]
    "fields"=>[{
        "id"=>"11",
        "_destroy"=>"false",
        "position"=>"1",
        "value"=>"Foobar",
        "fields"=>[{
            "id"=>"",
            "_destroy"=>"false",
            "position"=>"1",
            "value"=>"Foobar child"
        }]
    }]
}
4

0 回答 0