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

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

Overview

Do not rename columns that are in use. It will cause down time in your application and is unsafe for pt-online-schema-change. Instead:

  1. Create a new column
  2. Backfill and write to the new column
  3. Add old column to ignored_columns in model
  4. Drop the old column

This is meaningful if the table has records in it. But even if the column is not in use, one can not rename it. ActiveRecord accesses old columns unless all queries explicitly SELECT other columns.

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 =
"Do not rename columns that are in use. It will cause down time in your application " \
"and is unsafe for pt-online-schema-change."

Instance Method Summary collapse

Instance Method Details

#on_block(node) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/rubocop/cop/migration/rename_column.rb', line 54

def on_block(node)
  return unless change_table_block?(node)

  block_arg = node.arguments.first
  return unless block_arg

  rename_calls(node, block_arg.name) do |rename_node|
    add_offense(rename_node)
  end
end

#on_send(node) ⇒ Object Also known as: on_csend



47
48
49
50
51
# File 'lib/rubocop/cop/migration/rename_column.rb', line 47

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

  add_offense(node)
end