Rails' ActiveRecord::Base
class defines an ==
method that returns true
if the objects are identical or they have the same ID.
I've overridden ==
in a couple of my Rails models to allow for more meaningful equality conditions. These work when I compare objects directly (e.g., through script/console
), but if I do something like my_array_of_models.include? other_model
, include?
always returns false
. even if the array contains an object that is "equal" (according to my definition).
I've fixed this by doing, e.g., my_array_of_models.any? { |el| el.attr == other_model.attr }
(which I think is the way you're encouraged to do comparisons, anyway), but I'm wondering: is it meaningful to override ==
in ActiveRecord models, or does ActiveRecord do something at a high level that renders such an overridden method useless (or worse, dangerous)?
Source
Here're my implementations of my overridden methods. There are two classes, User
and Contact
. Users
have unique email addresses, so ==
returns true if the email addresses are the same. Contact
is a bridge between Users
(like a "friend" relationship in social networking), and should return true
if they have the same user_id
.
class User < ActiveRecord::Base
def ==(other)
other.respond_to?(:email) and self.email == other.email
end
end
class Contact < ActiveRecord::Base
def ==(other)
if other.class == self.class
self.user == other.user
elsif other.kind_of? User
self.user == other
else
false
end
end
end
As I noted, it works when comparing directly (e.g., one_object == another_object
), but my_array_of_objs.include? included_obj
always returns false
.