我有一个javascript表单,允许用户在父对象下创建类别层次结构。
因此,使用自引用连接创建层次结构:
class DefaultCategory < ActiveRecord::Base
belongs_to :client
belongs_to :parent, :class_name => "DefaultCategory", :inverse_of => :children
has_many :children, :class_name => "DefaultCategory", :inverse_of => :parent
end
提交此表单时,我希望正确填充“parent_id”字段,但父级也可能是新记录,因此还没有ID。
到目前为止,我的尝试在解析为params之后看起来像这样:
{"default_categories_attributes"=>
{"new_category_1"=>
{"id"=>"", "parent_id"=>"", "name"=>"New Category 1"},
"new_category_2"=>
{"id"=>"", "parent_id"=>"new_category_1", "name"=>"New Category 2"},
"new_category_3"=>
{"id"=>"", "parent_id"=>"new_category_2", "name"=>"New Category 3 "},
"new_category_4"=>
{"id"=>"", "parent_id"=>"new_category_3", "name"=>"New Category 4"}
}
}
批量分配是否可以正确创建这些新记录并相互引用?可能通过将每个子类别嵌套到其父级的“children_attributes”中并获得顶级关联ID以某种方式向下复制?