Compare each value of two ActiveRecords returning a boolean variable

I use Ruby on Rails 3, and I have two ActiveRecord objects of the same class account as these:

# Account1 <Account id: 1, name: "Test name 1", surname: "Test surname 1", email: "...", ...> 

and

 # Account2 <Account id: 2, name: "Test name 2", surname: "Test surname 2", email: "...", ...> 

How do you compare each attribute of Account1 with the corresponding attributes of Account2 in several lines of code to check if the values ​​are equal? I should get the output "true" if all the values ​​of Account1 are equal to the values ​​of Account2, otherwise "false", even if only one is different.

+4
source share
2 answers
 account1.attributes == account2.attributes 

There, it's pretty short. Note that the identifier is included in these attributes. You can use .clone for both to avoid this, or exclude it from hash attributes in some other way. For instance:

 account1.attributes.except('id') == account2.attributes.except('id') 
+18
source
 (account1.attributes.keys - ["id"]).inject(true) { |memo, att| memo && (account1[att] == account2[att]) } 
0
source

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


All Articles