Koren Leslie Cohen

  • About
  • Blog
  • Contact

6 comments

Ruby / Rails

Rails: Rename a Database/Table Column

December 21, 2014 by Koren Leslie Cohen

devise redirects

There are a variety of reasons you may want or need to rename a database or table column in your Rails application. Accomplishing this is quite simple.

Create a New Migration

This can be called whatever you’d like:

rails g migration ChangeNames
Update Your Migration

You can change as many column names as you want in this migration:

class ChangeNames < ActiveRecord::Migration
  def change
    rename_column :table, :old_name, :new_name
    rename_column :table, :old_name, :new_name
  end
end
Migrate
rake db:migrate

Make sure you replace all references to the previous column names in your application, or you’ll experience errors when accessing views containing the former names. The data will automatically be transferred.

  • About
  • Latest Posts
Connect
Koren Leslie Cohen
Product manager at Facebook. Former senior product manager at Dollar Shave Club in Los Angeles and software engineer at J.Crew / Madewell in New York City. Recovering trial lawyer.
Connect
Latest posts by Koren Leslie Cohen (see all)
  • PM Career Story - April 28, 2022
  • How to Transition into Product Management - December 26, 2017
  • What I’ve Learned in My First Few Months as a Product Manager - October 14, 2015

Related Posts

Nested Arrays, Hashes & Loops in Ruby
Creating a Simple Search in Rails 4

Share

Facebook Google+ Twitter Pinterest Email

Comments Cancel reply

Your email address will not be published. Required fields are marked *

*

code

  1. Wellington Torrejais da Silva says

    April 2, 2015 at 1:58 pm

    Thanks

    Reply
    • Koren Leslie Cohen says

      April 2, 2015 at 2:02 pm

      No prob 😉

      Reply
  2. Andre says

    August 31, 2015 at 2:30 pm

    this was very helpful and simple !!!!
    thank you

    Reply
    • Koren Leslie Cohen says

      September 15, 2015 at 1:46 pm

      You’re welcome!

      Reply
  3. Francisco says

    June 20, 2016 at 9:50 am

    If you’d need to change a table name you can do it like this:

    rename_table :old_table_name, :new_table_name

    Reply
  4. min says

    August 5, 2016 at 5:46 am

    Is it possible to add ‘remove_column’ or ‘add_column’ instead of using ‘rename_column’?
    For example,

    rails g migration ChangeNames

    class ChangeNames < ActiveRecord::Migration
    def change
    add_column :table, :name, :type
    remove_column :table, :name
    end
    end

    Reply

Back to Blog

  • GitHub
  • Instagram
  • LinkedIn
  • RSS
  • Twitter

Looking for something?

Copyright 2023 Koren Leslie Cohen