ruby on rails overriding equals
I have a model user.rb (it's an ActiveRecord::Base, not sure if its relevant to the discussion)
In certain views, I compare two users via:
<% if current_user == 开发者_开发技巧user %>
The result is undeterministic(sometimes the result is true, and sometimes it's false), and I'm not sure why.
If I switch it to
<% if current_user.id == user.id %>
It works as expected. But then I need to handle the case where the user(s) can be null.
My question is, what's going on here?
Why does user1 == user2 fail here?
Should I be overriding == , or
Should I be using an alternative method such as equal?, ===, or eql?
Shouldn't the fact that user.rb is an ActiveRecord::Base mean == by default compares the id fields already?
If you look at the source code of ==
# File lib/active_record/base.rb, line 2427
2427: def ==(comparison_object)
2428: comparison_object.equal?(self) ||
2429: (comparison_object.instance_of?(self.class) &&
2430: comparison_object.id == id &&
2431: !comparison_object.new_record?)
2432: end
You can see that it should return true when the object ids match. If your code <% if current_user == user %>
is failing for the same user object you have definitely got something odd going on.
Can you post that code snippet in context?
From http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-%3D%3D
Returns true if comparison_object is the same exact object, or comparison_object is of the same type and self has an ID and it is equal to comparison_object.id.
Note that new records are different from any other record by definition, unless the other record is the receiver itself. Besides, if you fetch existing records with select and leave the ID out, you’re on your own, this predicate will return false.
Note also that destroying a record preserves its ID in the model instance, so deleted models are still comparable.
It should match current_user == user
How are you fetching current_user object?
if you want to go further on equality in ruby, take a look at this very good blog post:
http://www.skorks.com/2009/09/ruby-equality-and-object-comparison/
Hope this helps you understand.
精彩评论