So, the variable bob_cats is changing as the collection changes.
However if I replace the second line with bobs_cats =
bob.cats.find(:all) it behaves I would expect, i.e. behaves as an array
of Cat objects, and is not affected by changes to the collection.
changes. IS that expected?
bobs_cats = bob.cats
Can anyone shed any light on this?
=> 18829402
=> 18829402
now there are two distinct objects
Just to elaborate a little further: this is happening because the
object in question is an association proxy object. It gets created
the first time, and then cached:
The object_id of things has changed, though things has not been
reassigned. Rather bizarre from the Ruby point of view, and not
particularly to my taste; I prefer to know what’s going to happen when
I assign to a variable, and to be the one who decides if and when the
binding will change. But it’s unlikely to cause trouble in practice,
as far as I can tell.
David
–
Q. What’s a good holiday present for the serious Rails developer?
A. RUBY FOR RAILS by David A. Black (Ruby for Rails)
aka The Ruby book for Rails developers!
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)
OK. That makes sense. Guess I never quite connected (in my mind) the
Array of AR objects that is bob.cats and the bob.cats.create or
whatever. I’m guess the additional has_many methods are available to the
array through some sort of method_missing magic?
But I’ve come across some unexpected behaviour, and I wonder if anyone
cat belongs_to :human
However if I replace the second line with bobs_cats =
=> 18829402
things = tag.things
tag.things.reload
David
David
Thanks for this. Have been getting so much into the Ruby aspect of Rails
recently (not least thanks to your excellent book) sort of forgot about
some of the strange things that Rails does.
Cheers
Chris
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.