在第一次迁移后更改字段名称时,Rails db迁移中止错误

时间:2016-09-14 04:51:09

标签: ruby-on-rails sqlite database-migration

我已经将add_column:users,:confirmed_at(confirmation_at),:datetime命名为偶然。所以我将其更改为相应的字段名称:(confirmed_at)

然后我输入:rake db:在命令行中回滚。由于某种原因,它已被中止,但是首先我的Rails db迁移文件代码:

class AddConfirmableToDevise < ActiveRecord::Migration
  def up
    add_column :users, :confirmation_token, :string
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_sent_at, :datetime

    add_index :users, :confirmation_token, unique: true
  end

  def down
    remove_column :users, :confirmation_token, :confirmed_at, :confirmation_sent_at
  end
end

迁移后出错:

tzurch:~/workspace (gravitar) $ rake db:migrate:redo

#the error that came up below
_________________________________________________
== 20160902201448 AddFullnameToUser: reverting ================================

-- remove_column(:users, :fullname, :string)

-> 0.0207s

== 20160902201448 AddFullnameToUser: reverted (0.0284s) =======================

== 20160902201448 AddFullnameToUser: migrating ================================

-- add_column(:users, :fullname, :string)

-> 0.0008s

== 20160902201448 AddFullnameToUser: migrated (0.0009s) =======================

== 20160913221959 AddConfirmableToDevise: migrating ===========================

-- add_column(:users, :confirmation_token, :string)

-> 0.0009s

-- add_column(:users, :confirmed_at, :datetime)

-> 0.0005s

-- add_column(:users, :confirmation_sent_at, :datetime)

rake aborted!

StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: duplicate column name: confirmation_sent_at: ALTER TABLE "users" ADD "confirmation_sent_at" datetime:

2 个答案:

答案 0 :(得分:0)

我想你在db

中已经有了这个表中的confirmation_sent_at字段

答案 1 :(得分:0)

此处的问题是您用于删除列的语法是错误的。

正确的语法是remove_column

remove_column(table_name, column_name, type = nil, options = {})

使用

更改迁移
class AddConfirmableToDevise < ActiveRecord::Migration
  def up
    add_column :users, :confirmation_token, :string
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_sent_at, :datetime

    add_index :users, :confirmation_token, unique: true
  end

  def down
    remove_column :users, :confirmation_token
    remove_column :users, :confirmed_at
    remove_column :users, :confirmation_sent_at

    remove_index :users, :confirmation_token
  end
end

或者完全删除down迁移并将up替换为change,rails会知道如何回滚:

class AddConfirmableToDevise < ActiveRecord::Migration
  def change
    add_column :users, :confirmation_token, :string
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_sent_at, :datetime

    add_index :users, :confirmation_token, unique: true
  end
end