对现有模型使用gem'devise'时出错

时间:2019-03-31 09:44:55

标签: ruby-on-rails rubygems

我只是尝试添加gem'devise',但遇到了一些错误。

但是在此之前,我创建了一个这样的模型用户:

    class CreateUsers < ActiveRecord::Migration[5.2]
    def change
    create_table :users do |t|
        t.string :name
        t.string :email
        t.integer :role
        t.string :password_digest
        t.timestamps
    end
    end
    end

然后我运行命令“ rails generate devise User”,它创建了一个迁移 add_devise_to_user:

    class AddDeviseToUsers < ActiveRecord::Migration[5.2]
    def self.up
    change_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
    # Uncomment below if timestamps were not included in your 
    original model.
    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

    def self.down
    # By default, we don't want to make any assumption about how to 
    roll back a migration when your
    # model already existed. Please edit below which fields you 
    would like to remove in this migration.
    raise ActiveRecord::IrreversibleMigration
    end
    end

每当我尝试运行rails db:migrate时,终端就会向我显示这些错误

    == 20190331081250 AddDeviseToUsers: migrating =================================

-change_table(:users) 铁轨中止了! StandardError:发生错误,所有以后的迁移都被取消:

Mysql2 :: Error:重复的列名'email':ALTER TABLE users添加email varchar(255)DEFAULT''NOT NULL

原因: ActiveRecord :: StatementInvalid:Mysql2 :: Error:重复的列名'email':ALTER TABLE users添加email varchar(255)DEFAULT''NOT NULL

我检查了人们提出的问题和解决方案,但没有一个能帮助我解决这个问题(我是这里的新手)

1 个答案:

答案 0 :(得分:0)

阻止change_table,将列添加到现有表users中。在change_table中,您尝试添加列email,但此列已存在于表users中。此列是在您的首次迁移中创建的。

您应该在设计迁移中评论以下字符串:

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

change_table(禁止进入)方法之后,在设计迁移中添加跟随字符串:

change_column :users, :email, :string, null: false, default: ""