How to rename column name in Rails


Ruby On Rails - SapidLabs

Rails rename_column

Rails provides a simple method rename_column which can be used in a migration.


Example: Say you have a User model in your rails application, with a db field as name. Now, you want to change the name of the column. we should generate a migration by using rails g migration change_users_name_to_title. Our migration should look like:

class ChangeUsersNameToTitle < ActiveRecord::Migration[6.0]
  def change
    rename_column :users, :name, :title
  end
end

Now run rails db:migrate in order to make the changes to the database.

## Rename column method
rename_column(:table_name, :column_name, :new_column_name)


Verify from the schema.rb to see if the field actually changed.


Recommended Posts

Rails 5 adds OR Activerecord method
This or method was introduced in Rails 5, It returns a new ActiveRecord::Relation which is...
Descendants vs Subclasses in Ruby
Descendants has been a part of Rails ActiveSupport::DescendantsTracker for quite a while. However, Class#subsclasses is...
Ruby 3.1 adds subclasses method
Ruby 3.1 adds Class#subclasses method, which returns an array of subclasses directly inheriting from the...