Check if a cell in an ActiveRecord Array have been changed

Viewed 286

I'm using PostgreSQL which supports arrays, which is very convenient. Sometimes I need to see if an element have been changed.

I know we can do this:

MyActiveRecordArray.changed?
=> true

But is there a way do this:

MyActiveRecordArray[0].changed?

Thank you for your answers and help!

3 Answers

Here is the solution I come up with, thanks to your answer

changes_index = []  
old_array, new_array  = model.changes['array_field']  
new_array.each_with_index { |x, i| changes_index << i if x != old_array[i] }

You can ask directly your ActiveRecord instance if a specific attribute has changed by using attribute_name_changed? method.

On your case:

MyModel.active_record_array_changed?

This would return true or false depending whether the specific attribute has changed.

Related