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)),其中用户名和所有列设计需要操作。所以你的第二次迁移是没有必要的。它会失败,因为表已经存在。 (也包括时间戳字段)如果您想要将其他字段添加到用户表中,可以在初始迁移中添加它们,或者进行迁移以更新用户表。不要忘记将这些字段添加为用户模型中的可访问属性。