
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.
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
Thanks
No prob 😉
this was very helpful and simple !!!!
thank you
You’re welcome!
If you’d need to change a table name you can do it like this:
rename_table :old_table_name, :new_table_name
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