Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate object_changes field for rows created prior to that field being added

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

like image 323
dane Avatar asked Dec 14 '25 08:12

dane


1 Answers

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
like image 106
TMaYaD Avatar answered Dec 16 '25 23:12

TMaYaD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!