I've been trying to find a solution to the following problem. I have three types of objects: A,B och C. C contains B and B contains A. What i wanna do is this:
A.new(:b = > B.new(:c => C.new)).save
but that failes, and I'm forced to do it the other way around. Any ideas on how I can write it? The current code looks like this:
B.transaction do |t|
b = B.create(:object => @object)
C.create(:b => b)
end
The best way to do this is to use accepts_nested_attributes_for.
You should put in model A:
accepts_nested_attributes_for :b_model
in model B:
accepts_nested_attributes_for :c_model
Then type:
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])
See examples here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With