Active Record, and multiple models in memory


#1

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