How can I rename a database column in a Ruby on Rails migration ?

How can I rename a database column in a Ruby on Rails migration ?

Asked on December 13, 2018 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    Here is  solution,

    rename_column :table, :old_column, :new_column

    Update:

     The Separate migration to solve:

    script/generate migration FixColumnName
    # creates db/migrate/xxxxxxxxxx_fix_column_name.rb
    

    Try this code:

    # 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
    
    Answered on December 13, 2018.
    Add Comment

    Solution:

        The IMO can better use rake db:rollback. Then edit your migration and again type rake db:migrate. if you have data in the column and you no need to lose, then use rename_column

    Answered on December 13, 2018.
    Add Comment

    Try this simplest method:

    Under Available Transformations

    rename_column(table_name, column_name, new_column_name):
    

    Renames a column but keeps the type and content.

    See this below link:http://api.rubyonrails.org/classes/ActiveRecord/Migration.html 

    Answered on December 13, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.