I have implemented object_changes after using paper_trail in production for quite some time. Is there a way for me to populate the object_changes field for objects that were created prior to adding this field? I assume there should be.
paper_trail
This should get the job done. You can further optimise this by excluding the papertrail excluded attributes like timestamps etc.
class AddChangesetsToVersions < ActiveRecord::Migration[5.0]
def change
add_column :versions, :object_changes, :jsonb
reversible do |dir|
dir.up do
PaperTrail::Version.find_each do |version|
old_attr = version.object || {}
new_attr = version.next&.object || version.item&.attributes_before_type_cast || {}
changed_attrs = (old_attr.keys | new_attr.keys).delete_if { |attr|
old_attr[attr] == new_attr[attr]
}
changes = changed_attrs.map {|attr|
[
attr,
[
old_attr[attr],
new_attr[attr]
]
]
}.to_h
version.update_column :object_changes, changes
end
end
end
end
end
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