views:

29

answers:

3

Assume this code

instance1 = MyModel.find(1)
instance2 = MyModel.find(1)

Is instance1.equals(instance2) true? (i.e. are they the same objects?)

And after this:

instance1.my_column = "new value"

Does instance2.my_column also contain "new value"?

+2  A: 

No, it doesn't. You can keep instance2 in sync with reload.

instance1 = MyModel.find(1)
instance2 = MyModel.find(1)

instance1.my_column = "new value"
instance2.my_column 
# => old value

instance1.save!
instance2.my_column 
# => old value

instance2.reload
instance2.my_column 
# => new value

Keep in mind you must save instance1 changes to the database.

Simone Carletti
oh gosh am I a slowpoke :)
neutrino
+2  A: 
  1. instance1.equals(instance2) is not true. In Rails they are not the same objects. AFAIK, In Merb they would
  2. instance2.my_column won't contain a new value, unless you save instance1 and do instance2.reload
neutrino
+2  A: 

weppos is completely correct for the second part of your question. For the first part then there are some subtle difference to equality dependent on how you are testing.

instance1.eql?(instance2)
  => true

.eql? checks if the objects have the same type and value whereas

instance1.equal?(instance2)
  => false

.equal? checks if the objects have the same object_id and returns false because

instance1.object_id
  => 18277960
instance2.object_id
  => 18271750

There is a good article on this subject here

Steve Weet