你可以为rename_column
创建自定义生成器
ActiveSupport.on_load(:active_record) do
ActiveRecord::Generators::MigrationGenerator.class_eval do
alias :origin_create_migration_file :create_migration_file
def create_migration_file
if file_name =~ /^rename_(.*)_to_(.*)_on_(.*)/
@old_column = $1
@new_column = $2
@table_name = normalize_table_name($3)
@migration_template = File.join(Rails.root, "lib", "generators", "ext", "templates", "rename_column_migration.rb")
validate_file_name!
migration_template @migration_template, File.join(db_migrate_path, "#{file_name}.rb")
else
origin_create_migration_file
end
end
end
end
class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
def change
rename_column :<%= table_name %>, :<%= @old_column %>, :<%= @new_column %>
end
end
require File.join(Rails.root, "lib", "generators", "ext", "rename_column.rb")
现在你可以像这样自动生成
rename_column
。
$ rails g migration RenameTitleToNameOnProducts
create db/migrate/20210906044147_rename_title_to_name_on_products.rb
class RenameTitleToNameOnProducts < ActiveRecord::Migration[6.1]
def change
rename_column :products, :title, :name
end
end