0

我正在嘗試實現Devise身份驗證庫,並且還添加了可能需要使用的專用於我自己的應用程序的列。執行用戶遷移時的錯誤

我運行rake migration命令,出現一個奇怪的錯誤。這裏是我的devise_create_users文件:

class DeviseCreateUsers < ActiveRecord::Migration 
    def self.up 
    create_table(:users) do |t| 
     t.database_authenticatable :null => false 
     t.recoverable 
     t.rememberable 
     t.trackable 

     # t.encryptable 
     # t.confirmable 
     # t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both 
     # t.token_authenticatable 


     t.timestamps 
    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 
    # add_index :users, :authentication_token, :unique => true 
    end 

    def self.down 
    drop_table :users 
    end 
end 

和最小create_users文件

class CreateUsers < ActiveRecord::Migration 
    def self.up 
    create_table :users do |t| 

     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :users 
    end 
end 

但奇怪的是,當我運行遷移,我得到這個錯誤:

Mysql2::Error: Table 'users' already exists: CREATE TABLE `users` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `email` varchar(255) DEFAULT '' NOT NULL, `encrypted_password` varchar(128) DEFAULT '' NOT NULL, `reset_password_token` varchar(255), `reset_password_sent_at` datetime, `remember_created_at` datetime, `sign_in_count` int(11) DEFAULT 0, `current_sign_in_at` datetime, `last_sign_in_at` datetime, `current_sign_in_ip` varchar(255), `last_sign_in_ip` varchar(255), `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB 

哪是非常奇怪的,因爲我從未在上面列出的文件中提及任何這些列。額外的列從哪裏來?我的第二個create_users文件應該是更新而不是創建?

謝謝!

回答

3

您遇到此問題是因爲您試圖創建表users兩次。

您的第一次遷移將創建表users並且您看到的奇怪列由devise創建。

如果您需要更新您的列使用:

class CreateUsers < ActiveRecord::Migration 
    def self.up 
    add_column :table_name, :new_column_name, :data_type #add new column 
    remove_column :table_name, :column_to_remove   #remove an existing column 
    end 

    ... 
end 

看看Migrations以獲取更多信息。

+0

你知道Devise指定這些列的位置嗎?我無法追查他們。 – GeekedOut 2011-05-20 18:29:49

+0

@GeekedOut它們在這個文件中定義https://github.com/plataformatec/devise/blob/master/lib/devise/schema.rb,它們根據您的遷移選擇進行應用。 – JCorcuera 2011-05-20 18:35:36

2

第一次遷移將創建一個表(create_table(:users)),其中用戶名和所有列設計需要操作。所以你的第二次遷移是沒有必要的。它會失敗,因爲表已經存在。 (也包括時間戳字段)如果您想要將其他字段添加到用戶表中,可以在初始遷移中添加它們,或者進行遷移以更新用戶表。不要忘記將這些字段添加爲用戶模型中的可訪問屬性。