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

I wrongly named a column hased_password instead of hashed_password .

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


rename_column :table, :old_column, :new_column

Update:

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

script/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

An update for Rails 3.1

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"

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

Thank you, Luke && Turadg , for bringing up the topic.

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


An update for Rails 4

While creating a Migration as for renaming a column, Rails 4 generates a change method instead of up and down as mentioned in the above answer. The generated change method is as below :

$ > rails g migration ChangeColumnName

which will create a migration file similar to this :

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

IMO, in this case, better use rake db:rollback . Then edit your migration and again type rake db:migrate . However, if you have data in the column you don't want to lose, then use rename_column .


http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Under Available Transformations

rename_column(table_name, column_name, new_column_name):

Renames a column but keeps the type and content.

链接地址: http://www.djcxy.com/p/8282.html

上一篇: 如何在Rails 4中使用关注点

下一篇: 如何在Ruby on Rails迁移中重命名数据库列?