Non-tech founder’s guide to choosing the right software development partner Download Ebook
Home>Blog>Renaming-keys-in-postgres-json-migration-template-for-gem-recorder

Renaming keys in PostgreSQL JSON / Migration template for gem Recorder

In our project, we used gem Recorder. It saves changes in jsonb format.

Once we need to rename a column in model Contact, but we didn't want to lose logs.

I introduce you template of migration for this case.


class RenameOldColumnToNewColumn < ActiveRecord::Migration[5.2]

  def up

    rename_column :contacts, :old_column, :new_column



    execute <<~SQL

      UPDATE recorder_revisions SET data = jsonb_set(data #- '{changes,old_column}', '{changes,new_column}', data#>'{changes,old_column}') WHERE data#>'{changes}'?'old_column';

    SQL

  end



  def down

    rename_column :contacts, :new_column, :old_column



    execute <<~SQL

      UPDATE recorder_revisions SET data = jsonb_set(data #- '{changes,new_column}', '{changes,old_column}', data#>'{changes,new_column}') WHERE data#>'{changes}'?'new_column';

    SQL

  end

end

You can simple replace contacts, new_column and old_column to your table name and columns names.

Do you have an idea? Launch it with us!
By submitting this form, you agree with JetRockets’ Privacy Policy