Ruby on rails exceeding equal

I have a user.rb model (this is ActiveRecord :: Base, not sure if it is relevant to the discussion)

In some views, I am comparing two users with:

<% if current_user == user %>

The result is undefined (sometimes the result is true, and sometimes 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 may be null.

My question is: what is going on here?

Why does user1 == user2 not work here?

Should I override == or

Should I use an alternative method like equal ?, === or eql?

Shouldn't user.rb be an ActiveRecord :: Base mean == value by default already comparing id fields?

+3
source share
3 answers

==

      # 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

, true, . <% if current_user == user %> , - .

?

+3

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-%3D%3D

true, compare_object self , comparison_object.id.

, , . , ID out, youre , false.

, , - .

current_user == user

current_user?

+1

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.

+1
source

Source: https://habr.com/ru/post/1785873/


All Articles