17

I want to auto generate a migration file that looks like this:

class RenameDatabaseColumn < ActiveRecord::Migration
  def change
    rename_column :events, :subcategory, :subcategory_id
  end
end

Is there some way to format my

rails g migration ~rename_column_events_subcategory_subcategory_id~

or something like that to auto generate that file?

Dan Baker
  • 1,757
  • 3
  • 21
  • 36
  • possible duplicate of [How can I rename a database column in a Rails migration?](http://stackoverflow.com/questions/1992019/how-can-i-rename-a-database-column-in-a-rails-migration) – rails_id Jul 16 '14 at 14:34

3 Answers3

15

No, There is no auto-generation command for "renaming" columns.

Refer Source Code. Auto generator understands only "to","from","add","remove","join_table","create"

Rahul garg
  • 9,202
  • 5
  • 34
  • 67
0

There is no auto generate command exists as of now to rename the column. You need to manually change it and then run rake db:migrate

Pramod Itagi
  • 191
  • 6
0

you could create custom generator for rename_column

# lib/generators/ext/rename_column.rb
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

# lib/generators/ext/templates/rename_column_migration.rb.tt
class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
  def change
    rename_column :<%= table_name %>, :<%= @old_column %>, :<%= @new_column %>
  end
end

# config/initializers/ext_core.rb
require File.join(Rails.root, "lib", "generators", "ext", "rename_column.rb")

Now you could auto generate rename_colum like this

$ rails g migration RenameTitleToNameOnProducts
create    db/migrate/20210906044147_rename_title_to_name_on_products.rb

# result
class RenameTitleToNameOnProducts < ActiveRecord::Migration[6.1]
  def change
    rename_column :products, :title, :name
  end
end
Lam Phan
  • 3,405
  • 2
  • 9
  • 20