Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two records and get the names of the changed columns in rails active record

i need to compare two active records and get the name of the changed column

#<Evaluation id: 1, name: "Foo", status: "yes", comments: "can be better", created_at: "2017-05-09 12:00:00", updated_at: "2017-05-09 12:00:00">    
#<Evaluation id: 2, name: "Foo", status: "yes", comments: "keep up the good work", created_at: "2017-05-09 12:05:00", updated_at: "2017-05-09 12:05:00">

I need to compare these two records and get the names of the changed columns. In this case :comments, :created_at, :updated_at

I have tried using methods like eql?, record1.attributes.except('id') == record2.attributes.except('id')

These only return either true or false I need to get the column names as well. This can be done by comparing each column but i am looking for any other option.

like image 299
Aditya Y Avatar asked Dec 18 '22 07:12

Aditya Y


1 Answers

You can use a small method to do this for you :

def diff_active_record(record_a, record_b)
   (record_a.attributes.to_a - record_b.attributes.to_a).map(&:first)
end

This method will take the two active_record objects(in this case : record_a , record_b ) to compare and generate an array of attribute names that have changed.

You may use it like this:

diff_active_record(Evaluation.find(1), Evaluation.find(2)) 

The above would result in [:id, :comments, :created_at, :updated_at]

like image 109
bitsapien Avatar answered Jan 13 '23 11:01

bitsapien