Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload