1578

I wrongly named a column hased_password instead of hashed_password.

How do I update the database schema, using migration to rename this column?

0

32 Answers 32

2497
rename_column :table, :old_column, :new_column

You'll probably want to create a separate migration to do this. (Rename FixColumnName as you will.):

bin/rails generate migration FixColumnName
# creates  db/migrate/xxxxxxxxxx_fix_column_name.rb

Then edit the migration to do your will:

# db/migrate/xxxxxxxxxx_fix_column_name.rb
class FixColumnName < ActiveRecord::Migration
  def self.up
    rename_column :table_name, :old_column, :new_column
  end

  def self.down
    # rename back if you need or do something else or do nothing
  end
end

For Rails 3.1 use:

While, the up and down methods still apply, Rails 3.1 receives a change method that "knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate down method".

See "Active Record Migrations" for more information.

rails g migration FixColumnName

class FixColumnName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end

If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again:

rename_column :table_name, :old_column1, :new_column1
rename_column :table_name, :old_column2, :new_column2
...

You could use change_table to keep things a little neater:

class FixColumnNames < ActiveRecord::Migration
  def change
    change_table :table_name do |t|
      t.rename :old_column1, :new_column1
      t.rename :old_column2, :new_column2
      ...
    end
  end
end

Then just db:migrate as usual or however you go about your business.


For 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:

$ > rails g migration ChangeColumnName

which will create a migration file similar to:

class ChangeColumnName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end
8
  • 31
    self.down should always be the opposite of self.up, so "if you need or do something else or do nothing" isn't really recommended. Just do: rename_column :table_name, :new_column, :old_column Aug 29, 2011 at 15:21
  • 3
    While it's normal practice to revert what you did in self.up I would not say self.down "should always be opposite". In depends on the context of your migration. Just putting the "opposite" might not be the "right" down migration.
    – nowk
    Aug 29, 2011 at 16:36
  • 25
    In Rails 3.1 you can replace def self.up and def self.down with def change and it'll know how to rollback.
    – Turadg
    Sep 9, 2011 at 21:57
  • 3
    Turadg - *it'll know how to rollback most of the time. I find the change method isn't full proof, so tend to use up and down methods for complex migrations. Oct 19, 2014 at 9:20
  • 8
    Does renaming remove index?
    – mc9
    Apr 12, 2015 at 11:43
71

In my opinion, in this case, it's better to use rake db:rollback, then edit your migration and again run rake db:migrate.

However, if you have data in the column you don't want to lose, then use rename_column.

6
  • 44
    Even on a "team of one", if you have multiple instances of your app running, say in different environments or on multiple computers etc, managing edited migrations is a major pain. I only edit a migration if I just created it and realized it was wrong, and haven't run it literally anywhere else yet. Dec 9, 2013 at 1:18
  • 1
    I had to restart the server after that. Sep 6, 2015 at 19:03
  • 12
    This technique should only be used in a situation where your changes haven't yet been merged with your production branch, and others aren't dependent on data persistence. In most every production circumstance, this is NOT the preferred method. Jan 3, 2017 at 18:31
  • 6
    never ever do this kind of things.
    – new2cpp
    Feb 23, 2017 at 6:37
  • 7
    I like to say to my team: 'Migrations are free' The cost of editing a migration which has been released into the wild is high: I once spent a few hours working out why my code wasn't working before I realised another team member had gone back and edited a migration which I'd already run. So don't edit an existing migration, use a new one to change the schema, because... ...'Migrations are free!' (it's not strictly true, but it makes the point)
    – TerryS
    Sep 3, 2017 at 23:58
37

If the column is already populated with data and live in production, I'd recommend a step by step approach, so as to avoid downtime in production while waiting for the migrations.

First I'd create a db migration to add columns with the new name(s) and populate them with the values from the old column name.

class AddCorrectColumnNames < ActiveRecord::Migration
  def up
    add_column :table, :correct_name_column_one, :string
    add_column :table, :correct_name_column_two, :string

    puts 'Updating correctly named columns'
    execute "UPDATE table_name SET correct_name_column_one = old_name_column_one, correct_name_column_two = old_name_column_two"
    end
  end

  def down
    remove_column :table, :correct_name_column_one
    remove_column :table, :correct_name_column_two
  end
end

Then I'd commit just that change, and push the change into production.

git commit -m 'adding columns with correct name'

Then once the commit has been pushed into production, I'd run.

Production $ bundle exec rake db:migrate

Then I'd update all of the views/controllers that referenced the old column name to the new column name. Run through my test suite, and commit just those changes. (After making sure it was working locally and passing all tests first!)

git commit -m 'using correct column name instead of old stinky bad column name'

Then I'd push that commit to production.

At this point you can remove the original column without worrying about any sort of downtime associated with the migration itself.

class RemoveBadColumnNames < ActiveRecord::Migration
  def up
    remove_column :table, :old_name_column_one
    remove_column :table, :old_name_column_two
  end

  def down
    add_column :table, :old_name_column_one, :string
    add_column :table, :old_name_column_two, :string
  end
end

Then push this latest migration to production and run bundle exec rake db:migrate in the background.

I realize this is a bit more involved of a process, but I'd rather do this than have issues with my production migration.

4
  • 2
    I like the thinking behind this, and I would +1 your repsonse but that data update would take a very long time to execute since it's going through rails and doing one row at a time. The migration would execute much faster with raw sql statements to update correctly named columns. For example, in the first db migration script, after adding the duplicate column names, execute "Update table_name set correct_name_column_one = old_name_column_one"
    – Gui LeFlea
    Sep 9, 2013 at 18:26
  • 1
    @mr.ruh.roh ^ Totally agree, should have written that in the first place. I've edited to reflect a single efficient sql statement. Thanks for the sanity check. Sep 14, 2013 at 2:04
  • 4
    What happens with entries in between moving to the new table and updating the code to use the new table? Could you not have potentially unmigrated data left over? Oct 8, 2014 at 15:59
  • 1
    while this is a 'safe' answer, I feel it is incomplete. Many people here say don't do this -why? persistence of data. And that is valid. Probably the least painful way accomplish the goal is to create the new fields, populate them with the data from the old columns, adjust controllers. If you want to delete the old columns, you'll certainly have to edit the views. The cost of keeping them is extra db space and some duplicate effort in controller. The tradeoffs are thus clear.
    – Jerome
    Jul 29, 2017 at 10:31
28

See the "Available Transformations" section in the "Active Record Migrations" documentation.

rename_column(table_name, column_name, new_column_name):

Renames a column but keeps the type and content.

1
21

Run this command to create a migration file:

rails g migration ChangeHasedPasswordToHashedPassword

Then in the file generated in the db/migrate folder, write rename_column as below:

class ChangeOldColumnToNewColumn < ActiveRecord::Migration
  def change
     rename_column :table_name, :hased_password, :hashed_password
  end
end
17

From the API:

rename_column(table_name, column_name, new_column_name)

This renames a column but keeps the type and content remains the same.

14

I had this challenge when working on a Rails 6 application with a PostgreSQL database.

Here's how I fixed it:

In my case the table_name was "Products", the old_column was "SKU" and the new_column was "ProductNumber".

  1. Create a migration file that will contain the command for renaming the column:

     rails generate migration RenameSKUToProductNumberInProducts
    
  2. Open the migration file in the db/migrate directory:

     db/migrate/20201028082344_rename_sku_to_product_number_in_products.rb
    
  3. Add the command for renaming the column:

     class RenameSkuToProductNumberInProducts < ActiveRecord::Migration[6.0]
       def change
         # rename_column :table_name, :old_column, :new_column
         rename_column :products, :sku, :product_number
       end
     end
    
  4. Save, and then run the migration command:

     rails db:migrate
    

You can now confirm the renaming of the column by taking a look at the schema file:

    db/schema.rb

If you are not satisfied with the renaming of the column, you can always rollback:

    rails db:rollback

Note: Endeavour to modify the column name to the new name in all the places where it is called.

12

If your code is not shared with other one, then best option is to do just rake db:rollback then edit your column name in migration and rake db:migrate. Thats it

And you can write another migration to rename the column

 def change
    rename_column :table_name, :old_name, :new_name
  end

Thats it.

1
  • rake db:rollback is a great suggestion. But like you said, only if the migration hasn't been pushed yet. Mar 14, 2019 at 13:47
12

Some versions of Ruby on Rails support the up/down methods for migration and if you have an up/down method in your migration, then:

def up
    rename_column :table_name, :column_old_name, :column_new_name
end

def down
    rename_column :table_name, :column_new_name, :column_old_name
end

If you have the change method in your migration, then:

def change
    rename_column :table_name, :column_old_name, :column_new_name
end

For more information see: Ruby on Rails - Migrations or Active Record Migrations.

9

As an alternative option, if you are not married to the idea of migrations, there is a compelling gem for ActiveRecord which will handle the name changes automatically for you, Datamapper style. All you do is change the column name in your model, and make sure you put Model.auto_upgrade! at the bottom of your model.rb, and viola! The database is updated on the fly.

See https://github.com/DAddYE/mini_record

Note: You will need to nuke db/schema.rb to prevent conflicts.

It is still in the beta phase and obviously not for everyone, but it is still a compelling choice. I am currently using it in two non-trivial production apps with no issues.

0
8

For Ruby on Rails 4:

def change
    rename_column :table_name, :column_name_old, :column_name_new
end
1
  • In case it saves someone looking it up, table_name is plural. E.g. :students
    – stevec
    Feb 18, 2022 at 11:29
8

If you need to switch column names you will need to create a placeholder to avoid a "duplicate column name" error. Here's an example:

class SwitchColumns < ActiveRecord::Migration
  def change
    rename_column :column_name, :x, :holder
    rename_column :column_name, :y, :x
    rename_column :column_name, :holder, :y
  end
end
8

Generate the migration file:

rails g migration FixName

which creates db/migrate/xxxxxxxxxx.rb.

Edit the migration to do your will:

class FixName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end
7

If the present data is not important for you, you can just take down your original migration using:

rake db:migrate:down VERSION='YOUR MIGRATION FILE VERSION HERE'

Without the quotes, then make changes in the original migration and run the up migration again by:

rake db:migrate
7

Simply create a new migration, and in a block, use rename_column as below.

rename_column :your_table_name, :hased_password, :hashed_password
6

Let's KISS. All it takes is three simple steps. The following works for Rails 5.2.

1 . Create a Migration

  • rails g migration RenameNameToFullNameInStudents

  • rails g RenameOldFieldToNewFieldInTableName - that way it is perfectly clear to maintainers of the code base later on. (use a plural for the table name).

2. Edit the migration

# I prefer to explicitly write theupanddownmethods.

# ./db/migrate/20190114045137_rename_name_to_full_name_in_students.rb

class RenameNameToFullNameInStudents < ActiveRecord::Migration[5.2]
  def up
    # rename_column :table_name, :old_column, :new_column
    rename_column :students, :name, :full_name
  end

  def down
            # Note that the columns are reversed
    rename_column :students, :full_name, :name
  end
end

3. Run your migrations

rake db:migrate

And you are off to the races!

5

Manually we can use the below method:

We can edit the migration manually like:

  • Open app/db/migrate/xxxxxxxxx_migration_file.rb

  • Update hased_password to hashed_password

  • Run the below command

    $> rake db:migrate:down VERSION=xxxxxxxxx
    

Then it will remove your migration:

$> rake db:migrate:up VERSION=xxxxxxxxx

It will add your migration with the updated change.

1
  • it won't be safe as you might loose data - if the column is already live. but can do for new column and/or table. Jul 23, 2015 at 12:05
5

Run rails g migration ChangesNameInUsers (or whatever you would like to name it)

Open the migration file that has just been generated, and add this line in the method (in between def change and end):

rename_column :table_name, :the_name_you_want_to_change, :the_new_name

Save the file, and run rake db:migrate in the console

Check out your schema.db in order to see if the name has actually changed in the database!

Hope this helps :)

5
 def change
    rename_column :table_name, :old_column_name, :new_column_name
  end
1
  • It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code. Feb 3, 2022 at 20:38
4

Generate a Ruby on Rails migration:

$:> rails g migration Fixcolumnname

Insert code in the migration file (XXXXXfixcolumnname.rb):

class Fixcolumnname < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end
4
$:  rails g migration RenameHashedPasswordColumn
invoke  active_record
      create    db/migrate/20160323054656_rename_hashed_password_column.rb

Open that migration file and modify that file as below(Do enter your original table_name)

class  RenameHashedPasswordColumn < ActiveRecord::Migration
  def change
    rename_column :table_name, :hased_password, :hashed_password
  end
end
3

In the console:

rails generate migration newMigration

In the newMigration file:

class FixColumnName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Dec 24, 2021 at 3:38
2

Open your Ruby on Rails console and enter:

ActiveRecord::Migration.rename_column :tablename, :old_column, :new_column
2

You have two ways to do this:

  1. In this type it automatically runs the reverse code of it, when rollback.

    def change
      rename_column :table_name, :old_column_name, :new_column_name
    end
    
  2. To this type, it runs the up method when rake db:migrate and runs the down method when rake db:rollback:

    def self.up
      rename_column :table_name, :old_column_name, :new_column_name
    end
    
    def self.down
      rename_column :table_name,:new_column_name,:old_column_name
    end
    
2

I'm on rails 5.2, and trying to rename a column on a devise User.

the rename_column bit worked for me, but the singular :table_name threw a "User table not found" error. Plural worked for me.

rails g RenameAgentinUser

Then change migration file to this:

rename_column :users, :agent?, :agent

Where :agent? is the old column name.

1

You can write a migration run the below command to update the column name:

rename_column :your_table_name, :hased_password, :hashed_password

Also, make sure that you update any usage of the old column name in your code with the new one.

1

A close cousin of create_table is change_table, used for changing existing tables. It is used in a similar fashion to create_table but the object yielded to the block knows more tricks. For example:

class ChangeBadColumnNames < ActiveRecord::Migration
  def change
    change_table :your_table_name do |t|
      t.rename :old_column_name, :new_column_name
    end
  end
end

This way is more efficient if we use it with other alter methods such as: remove/add index/remove index/add column. We can do things like:

Rename

t.rename :old_column_name, :new_column_name

Add column

t.string :new_column

Remove column

t.remove :removing_column

Index column

t.index :indexing_column
1
  • Please don't use "edited" or "update" type tags. Instead, incorporate the change as if it had always been there. If we need to know what changed we can look at the edit log. Feb 3, 2022 at 20:40
0

rails g migration migrationName

So you go to your generated migration and add:

rename_column :table, :old_column, :new_column

to the method

0

First you need to run

rails g migration create_new_column_in_tablename new_column:datatype
rails g migration remove_column_in_tablename old_column:datatype

and then you need to check db/migration you can check the details in the nem migration, if all the details is correct you need to run:

rails db:migrate
2
  • do you need migrate existed data from old_column to new_column ?
    – Lam Phan
    Sep 6, 2021 at 2:48
  • No, you don't need if you want just to rename it.
    – Saman
    Sep 6, 2021 at 23:40
0

Just generate the migration using:

rails g migration rename_hased_password

After that edit the migration and add the following line in the change method:

rename_column :table, :hased_password, :hashed_password

This should do the trick.

Not the answer you're looking for? Browse other questions tagged or ask your own question.