我一直在努力寻找解决以下问题的方法。我有三种类型的对象:A,B och C。C 包含 B,B 包含 A。我想做的是:
A.new(:b => B.new(:c => C.new)).save
但是失败了,我不得不反过来做。关于如何编写它的任何想法?当前代码如下所示:
B.transaction do |t|
b = B.create(:object => @object)
C.create(:b => b)
end
最佳答案
最好的方法是使用 accepts_nested_attributes_for
。
你应该输入模型A:
accepts_nested_attributes_for :b_model
在模型 B 中:
accepts_nested_attributes_for :c_model
然后输入:
params = { :a_model => {
:name => 'i belong to a',
:b_attributes => {
:title => 'I belong to b'
:c_attributes => {
:city => "I belong to c"
}
}
}
}
a = AModel.create(params[:a_model])
查看示例 here .
关于ruby - 如何在 Rails 3 中保存嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6459394/