我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
当前回答
我在rails 5.2上,试图重命名device User上的列。
rename_column位对我有效,但单数:table_name抛出了“User table not found”错误。Plural为我工作。
rails g RenameAgentinUser
然后将迁移文件更改为:
rename_column :users, :agent?, :agent
哪里:代理人?是旧的列名。
其他回答
rename_column :table, :old_column, :new_column
您可能需要创建一个单独的迁移来实现这一点。(根据需要重命名FixColumnName。):
bin/rails generate migration FixColumnName
# creates db/migrate/xxxxxxxxxx_fix_column_name.rb
然后编辑迁移以执行您的意愿:
# 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,请使用:
尽管向上和向下方法仍然适用,但Rails3.1收到了一个更改方法,该方法“知道如何迁移数据库,并在回滚迁移时反转数据库,而无需编写单独的向下方法”。
有关详细信息,请参阅“活动记录迁移”。
rails g migration FixColumnName
class FixColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
如果您恰好有一大堆列要重命名,或者需要反复重复表名:
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:像往常一样迁移,或者不管你怎么做。
对于轨道4:
在创建用于重命名列的Migration时,Rails4生成了一个更改方法,而不是上一节中提到的上下更改方法。生成的更改方法为:
$ > rails g migration ChangeColumnName
这将创建类似于以下内容的迁移文件:
class ChangeColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
只需使用以下方法生成迁移:
rails g migration rename_hased_password
之后,编辑迁移并在更改方法中添加以下行:
rename_column :table, :hased_password, :hashed_password
这应该会奏效。
如果需要切换列名,则需要创建占位符以避免出现“重复列名”错误。下面是一个示例:
class SwitchColumns < ActiveRecord::Migration
def change
rename_column :column_name, :x, :holder
rename_column :column_name, :y, :x
rename_column :column_name, :holder, :y
end
end
create_table的近亲是change_table,用于更改现有表。它以与create_table类似的方式使用,但向块提供的对象知道更多技巧。例如:
class ChangeBadColumnNames < ActiveRecord::Migration
def change
change_table :your_table_name do |t|
t.rename :old_column_name, :new_column_name
end
end
end
如果我们将其与其他alter方法一起使用,例如:remove/add index/remove index/add column,则这种方法更有效。我们可以做以下事情:
重命名
t.rename :old_column_name, :new_column_name
添加列
t.string :new_column
删除列
t.remove :removing_column
索引列
t.index :indexing_column
您有两种方法可以做到这一点:
在这种类型中,当回滚时,它会自动运行与其相反的代码。def更改重命名列:表名称,:旧列名称,:新列名称终止对于这种类型,它在rakedb:migrate时运行up方法,在rakedb:rollback时运行down方法:定义self.up重命名列:表名称,:旧列名称,:新列名称终止定义自己向下重命名列:表名称,:新列名称,:旧列名称终止