Is it possible to rename a column using a command like:
script/generate migration AddColumnToTable column:type
? Thanks.
While creating a Migration for renaming a column, Rails 4 generates a change method instead of up and down as mentioned in the above section. The generated change method is: class ChangeColumnName < ActiveRecord::Migration def change rename_column :table_name, :old_column, :new_column end end
If you want to rename a column, you can create a migration with the terminal command: rails g migration change_some_name. And then the code in the migration file should look something like this: class ChangeSomeName < ActiveRecord::Migration[6.0] def change rename_column :table_name, :old_name, :new_name end end
Start by creating a new migration: After the file has been created, specifying which column you want to change by adding a rename type on its place: Always run your RSpec tests after each change to the database to make it sure everything is working as intended. Also, please be careful with reserved names in Rails or SQL when renaming a column.
The process of renaming models in Rails can be very error prone. To just start renaming files and changing class names and search-replace variable names is fraught with peril – so I figured having the ability to repeat the process, in essence fix my scripting mistakes and “do-over,” was important.
Rails does have a migration command on the ActiveRecord ConnectionAdapter called rename_column
. You can generate a migration and then write the code yourself. example (MySQL):
script/generate migration rename_my_column_by_hand
Then edit the file it creates:
class RenameMyColumnByHand < ActiveRecord::Migration
def self.up
rename_column :my_table, :old_name, :new_name
end
def self.down
rename_column :my_table, :new_name, :old_name
end
end
It executes SQL like:
ALTER TABLE my_table CHANGE old_name new_name BIGINT;
Note This only renames the column, it won't rename any references you have to it on other tables.
Great question. The answer is, unfortunately, no. See Rails 2.3.5 source code:
lib/rails_generator/generators/components/migration/migration_generator.rb
The only keywords that are recognized by the migration generator are add
, remove
, and to
/from
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With