Forum: Ruby on Rails Active Record, and multiple models in memory

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.
485071faf1681a4106e4a3420144269a?d=identicon&s=25 David Williams (dwilliams)
on 2007-01-25 16:42
Hello,

I'm hoping some helpful soul may be able to explain to me why certain
bits of ActiveRecord are doing what they do. I've found a way to make it
work, but I don't actually understand _why_ it works.

I have two models, Boy and Girl which have these relationships

Boy: has_one :girl
Girl:  belongs_to :boy

In the Boy controller, I do this..

boy  = Boy.find(params[:id])
boy.update_car(AstonMartin)   # updates the car field from Skoda to
AstonMartin & saves
boy.girl.marry!

My problem is that the girl.marry! method still sees the value of the
car field as Skoda. Of course she is not happy & the are many
problems...

I've put some debug messages in..

puts boy.inspect, just before the boy.girl.marry!
puts girl.boy.inspect inside the girl.marry! routine

The boy.inspect showed an object id of X [not the active record id] and
car = AstonMartin

The girl.boy.inspect show an object id of Y [not the active record id]
and car = Skoda

If I do this, all is good

boy  = Boy.find(params[:id])
boy.update_car(AstonMarton)   # updates the car field from Skoda to
AstonMartin & saves
girl.boy = boy
boy.girl.marry!

Can someone please shed some light on this & let me know why the extra
girl.boy = boy is needed..?

Thank you for any assistance,

Dave
This topic is locked and can not be replied to.