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.
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')
(account1.attributes.keys - ["id"]).inject(true) { |memo, att| memo && (account1[att] == account2[att]) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With