Assigning objects...

I'm a Ruby Newbie (hey that rhymes!) and I suspect I haven't understood the syntax properly. I'm trying to assign one ActiveRecord object to the field of another and I think this should work:

>> org = Organisation.new => #<Organisation:0xb7652dd8 @new_record=true, @attributes={"fax_number"=>nil, "postal_address"=>nil, "name"=>nil, "org_structure_id"=>0, "location_address"=>nil, "tin"=>nil, "phone_number"=>nil, "contact"=>nil, "email_address"=>nil}> >> org.name = "Aces High Inc." => "Aces High Inc." >> person = NaturalPerson.new => #<NaturalPerson:0xb764997c @new_record=true, @attributes={"postal_address"=>nil, "fax_number"=>nil, "name"=>nil, "dob"=>nil, "phone_number"=>nil, "visa"=>nil, "mobile_number"=>nil, "email_address"=>nil, "nationality"=>nil}> >> person.name = "Fred Flinstone" => "Fred Flinstone" >> org.contact << person NoMethodError: You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occured while evaluating nil.<<        from (irb):13

My Organisation model looks like this:

class Organisation < ActiveRecord::Base belongs_to :org_structure belongs_to :natural_person, {:foreign_key => "contact"} has_many :natural_people, :through => :associates validates_associated :org_structure end

So by my understanding that second "belongs_to" call is supposed to enable me to make the assignment that's failing. It's 1 o'clock in the morning, maybe this will make sense after a sleep...

Well,

“org.contact << person” is the same as saying “org.contact.<<(person)”, which should make the error message clearer: contact is not defined. I guess you didn’t quite get what all the ActiveRecord meta-functions do to the class. The foreign key for :natural_person may be ‘contact’, but that is purely related to the database.

Sorry, now that I look at the relationships set up, I’m not sure I follow what is there. I understand what you are trying to do, but I don’t think you know what you’ve got there.

Either way, you will want this if all the associations are correct:

org.natural_people << person

Be sure to spend some more time first with Ruby itself, and then more time at the Rails docs (api.rubyonrails.com).

Jason