Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare each value of two ActiveRecords returning a boolean variable

I am using Ruby on Rails 3 and I have two ActiveRecord objects of the same class Account like 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 to compare in few lines of code each attribute of Account1 with the corresponding attributes of Account2 to test whether the values are equal? I should receive an output of 'true' if all the values of Account1 are equal to those of the Account2, otherwise 'false' even if only one is different.

like image 563
user502052 Avatar asked Dec 02 '22 03:12

user502052


2 Answers

account1.attributes == account2.attributes

There, that's pretty short. Note though that the id is included in those attributes. You could use .clone on both to avoid that, or exclude it from the attributes hash some other way. For example:

account1.attributes.except('id') == account2.attributes.except('id')
like image 104
noodl Avatar answered Dec 04 '22 06:12

noodl


(account1.attributes.keys - ["id"]).inject(true) { |memo, att| memo && (account1[att] == account2[att]) }
like image 38
Ben Lee Avatar answered Dec 04 '22 05:12

Ben Lee