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 = "开发者_JS百科new value"
Does instance2.my_column also contain "new value"?
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.
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
- instance1.equals(instance2) is not true. In Rails they are not the same objects. AFAIK, In Merb they would
- instance2.my_column won't contain a new value, unless you save instance1 and do instance2.reload
@Steve Weet
instance1 = User.find(1)
instance2 = User.find(1)
instance1 == instance2 # -> true
instance1.name = "zhangsan"
instance1 == instance2 # true (not false)
instance1.id = 0
instance1 == instance2 # false (this time)
instance1.id = 1
instance1 == instance2 # true (oh..)
so...this indicate that rails check the model equality depends on its id attribute.
BTW: I test is in ruby193/rails4rc
加载中,请稍侯......
精彩评论