Equality Gotcha of ActiveRecord Objects

 by Anand  on   22 Jul 2011

Two Activerecord objects when http://www.cprw.com/wp-content/themes/gazette/best-writing-paper.html compared over == operator returns true when they are instances of the same ‘model class’ && if they have same ‘id’ values. This operation is not an attribute-by-attribute comparison.

Beware, this behavior can give problems when you do a lot of == operations b/w Activerecord objects, in your application, in which case you need to override == operator of ActiveRecord::Base according to your needs.

Here is a sample behavior of == operator.

ruby-1.9.2-p180 :001 > p1 = Person.first
=> #<Person id: 1, name: “John”, email: “john@gmail.com”>
ruby-1.9.2-p180 :002 > p2 = Person.first
=> #<Person id: 1, name: “John”, email: “john@gmail.com”>
ruby-1.9.2-p180 :003 > p1.name = “somethingelse”
=> “somethingelse”
ruby-1.9.2-p180 :004 > p1.save
=> true
ruby-1.9.2-p180 :005 > p1
=> #<Person id: 1, name: “somethingelse”, email: “john@gmail.com”>
ruby-1.9.2-p180 :006 > p2
=> #<Person id: 1, name: “John”, email: “john@gmail.com”>
ruby-1.9.2-p180 :007 > p1 == p2
=> true

Tags: , , ,

Leave a comment