I have two models, Donor and Contribution, and have has_many and
belongs_to set respectively.
My question is regarding creation of associated objects. I’ll let the
code speak:
me = Donor.find(1)
contribution = me.contributions.create do |e|
e.amount = 164.00
e.category = Category.find(1)
end
I thought this was valid, but it doesn’t work properly - it appears to
create a new Contribution, but does not associate it with the Donor
(me). So, I tried this (using the build method):
contribution = me.contributions.build do |e|
e.amount = 164.00
e.category = Category.find(1)
e.save
end
This appears to have associated the object, but the contribution has no
values for the amount or category. Finally, I tried this (using the new
method):
contribution = me.contributions.new do |e|
e.donor = me
e.amount = 164.00
e.category = Category.find(1)
e.save
end
This does work, but I thought I could skip having to set the
association manually (shouldn’t the donor be inferred through the chain
me.contributions?)
Any help on this would be greatly appreciated - I’d just like to know if
I am assuming too much about the associations.