Class: RuboCop::Cop::Migration::RenameColumn

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/migration/rename_column.rb

Overview

Avoid renaming columns that are in use.

It will cause errors in your application. A safer approach is to:

  1. Create a new column

  2. Write to both columns

  3. Backfill data from the old column to the new column

  4. Move reads from the old column to the new column

  5. Stop writing to the old column

  6. Drop the old column

Examples:

# bad
class RenameUsersSettingsToProperties < ActiveRecord::Migration[7.0]
  def change
    rename_column :users, :settings, :properties
  end
end

# good
class AddUsersProperties < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :properties, :jsonb
  end
end

class User < ApplicationRecord
  self.ignored_columns += %w[settings]
end

class RemoveUsersSettings < ActiveRecord::Migration[7.0]
  def change
    remove_column :users, :settings
  end
end

Constant Summary collapse

MSG =
'Avoid renaming columns that are in use.'
RESTRICT_ON_SEND =
i[
  rename_column
].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ void

This method returns an undefined value.

Parameters:

  • node (RuboCop::AST::SendNode)


54
55
56
57
58
# File 'lib/rubocop/cop/migration/rename_column.rb', line 54

def on_send(node)
  return unless bad?(node)

  add_offense(node)
end