在提交表单时,操作基于多层嵌套属性创建记录.但是,根记录的ID(我称之为.save
)不会向下传播到关联.
下面是一个简化的例子:
class A
has_many :bs
# Note that A has direct access to C, without going through B
has_many :cs
accepts_nested_attributes_for :b
end
class B
# B has an :a_id field
belongs_to :a
has_many :cs
accepts_nested_attributes_for :c
end
class C
# note that C has a "circular relationship" to A,
# either directly through the :a_id field, or indirectly through B
belongs_to :a
belongs_to :b
end
根据上面的模型定义,这是一个有效负载示例:
{
a: {
name: "Model A",
bs_attributes: [{
name: "Model B",
cs_attributes: [{
name: "Model C"
}]
}]
}
}
并且该有效载荷将被送入:
A.create(payload)
当它在数据库中持久存在并且A被分配了一个ID时,我希望这个ID在子(B)和孙(C)记录上被自动设置为外键.这是不是可以使用Rails内置函数,通过简单的工作来实现呢?
我能想到的解决方案的一个例子是在关联上添加一个BEFORE_SAVE回调,以手动设置:a_id
字段.然而,这感觉可以用更简单的方式来完成.
目前正在开发Rails5,但如果有任何指导,我们将不胜感激.