Rails:如何在Ruby on Rails迁移中重命名数据库列? [英] Rails: How can I rename a database column in a Ruby on Rails migration?

查看:187
本文介绍了Rails:如何在Ruby on Rails迁移中重命名数据库列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我错误地将列命名为 hased_pa​​ssword ,而不是 hashed_pa​​ssword .

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

您可能需要创建一个单独的迁移来执行此操作.(请重命名 FixColumnName .):

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


对于Rails 3.1,使用:


For Rails 3.1 use:

虽然 up down 方法仍然适用,但是Rails 3.1接收到了 change 方法,该方法知道如何迁移数据库并进行反向操作.迁移时回滚而无需编写单独的down方法".

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".

有关更多信息,请参见"活动记录迁移".

See "Active Record Migrations" for more information.

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
...

您可以使用 change_table 保持整洁:

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

然后照常 db:migrate 进行,否则无论您从事何种业务.

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

对于Rails 4:

在创建用于重命名列的 Migration 时,Rails 4会生成一个 change 方法,而不是 up down 如上一节所述.生成的 change 方法是:

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

$ > rails g migration ChangeColumnName

它将创建类似于以下内容的迁移文件:

which will create a migration file similar to:

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

这篇关于Rails:如何在Ruby on Rails迁移中重命名数据库列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆