Forum: Ruby on Rails simple association question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Chris S. (Guest)
on 2006-02-16 03:04
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.
Ed C. (Guest)
on 2006-02-16 03:46
(Received via mailing list)
I don't think create() accepts a block. I would do:

me = Donor.find(1)
me.contributions.create( { :amount => 164.00, :category =>
Category.find(1) } )
Ed C. (Guest)
on 2006-02-16 03:49
(Received via mailing list)
You could also do:

my_contrib = Contribution.new
my_contrib.amount - 164.00
my_contrib.category = Category.find(1)

me = Donor.find(1)
me.contributions << my_contrib
This topic is locked and can not be replied to.