Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

renaming a column in Rails

Is it possible to rename a column using a command like:

script/generate migration AddColumnToTable column:type

? Thanks.

like image 785
Victor Avatar asked Feb 16 '10 22:02

Victor


People also ask

How to rename a column in rails 4?

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

How do I rename a column in a column migration?

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

How do I rename a column in RSpec?

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.

Can I rename models in rails?

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.


Video Answer


2 Answers

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.

like image 170
scottd Avatar answered Nov 01 '22 17:11

scottd


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.

like image 31
Alex Reisner Avatar answered Nov 01 '22 17:11

Alex Reisner