2016-07-17 12 views
0

我對Rails相當陌生,目前我正在安裝devise gem。Rails數據庫遷移失敗,並顯示「重複的列名:電子郵件」

當我創建了一個用戶模式,並試圖遷移數據庫:

$ rails generate devise User 
$ rake db:migrate 

我收到以下錯誤響應:

== 20160717064710 AddDeviseToUsers: migrating ================================= 
-- change_table(:users) 
rails aborted! 
StandardError: An error has occurred, all later migrations canceled: 

Mysql2::Error: Duplicate column name 'email': ALTER TABLE `users` ADD `email` varchar(255) DEFAULT '' NOT NULL 
Tasks: TOP => db:migrate 
(See full trace by running task with --trace) 

我不太確定的模式是什麼,但這裏是我的模式的副本。這是空的,我認爲這是假設是,直到該數據庫遷移:

ActiveRecord::Schema.define(version: 0) do 

end 

這裏是在DB我的移民文件的副本/遷移:

class DeviseCreateUsers < ActiveRecord::Migration[5.0] 
    def change 
    create_table :users do |t| 
     ## Database authenticatable 
     t.string :email,    null: false, default: "" 
     t.string :encrypted_password, null: false, default: "" 

     ## Recoverable 
     t.string :reset_password_token 
     t.datetime :reset_password_sent_at 

     ## Rememberable 
     t.datetime :remember_created_at 

     ## Trackable 
     t.integer :sign_in_count, default: 0, null: false 
     t.datetime :current_sign_in_at 
     t.datetime :last_sign_in_at 
     t.string :current_sign_in_ip 
     t.string :last_sign_in_ip 

     ## Confirmable 
     # t.string :confirmation_token 
     # t.datetime :confirmed_at 
     # t.datetime :confirmation_sent_at 
     # t.string 

:unconfirmed_email # Only if using reconfirmable 

      ## Lockable 
      # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 
      # t.string :unlock_token # Only if unlock strategy is :email or :both 
      # t.datetime :locked_at 


      t.timestamps null: false 
     end 

     add_index :users, :email,    unique: true 
     add_index :users, :reset_password_token, unique: true 
     # add_index :users, :confirmation_token, unique: true 
     # add_index :users, :unlock_token,   unique: true 
     end 
    end 

我是相當新到Rails,所以我實際上很遺憾這個錯誤的含義。我假設我顯然已經有一個名爲「email」的列。

另外,我註釋掉t.string:電子郵件,並鍵入以下內容:

rails db:rollback 
rails db:migrate 

而且我得到了目前存在的錯誤:

Mysql2::Error: Key column 'email' doesn't exist in table: CREATE UNIQUE INDEX `index_users_on_email` ON `users` (`email`) 

回答

0

在由設計,變化所產生的遷移文件行

t.string :email, null: false, default: ""

到:

t.change :email, :string, null: false, default: ""

,而不是試圖創建新的電子郵件科拉姆,遷移改變現有的制定

的規格

然後運行耙分貝:遷移

+0

未定義的方法爲#'變化」 GVS

+0

更新語法?你什麼意思? (對不起,我是新手) – GVS

+0

我在我的答案中更新了代碼。運行rake db:rollback,然後將遷移文件的電子郵件行更改爲我的答案中的第二個代碼行 –

0

@GVS試試這個:你已經無意中編輯了您的遷移文件。這看起來像你的問題在哪裏。

1.查找遷移文件,這條線上,其註釋掉或刪除它

:unconfirmed_email # Only if using reconfirmable 

您已經明顯改變了。那是什麼導致你的問題。它應該在上面幾行。

2.按照您的操作進行遷移回滾。

3.將郵件列留在那裏並重新運行遷移。

它現在應該工作。 (但是,如果您打算將電子郵件退出,則必須移除遷移底部的「add_index:users,:email,unique:true」行,並查看您的用戶模型並在其中進行相應的更改)

我希望這會有所幫助。如果它仍然不起作用回發你的錯誤,我會修改我的答案。

祝你好運!

RGDS

BKSpurgeon