gpt4 book ai didi

ruby-on-rails - Rails 数据库迁移失败并显示 “duplicate column name: email”

转载 作者:行者123 更新时间:2023-12-02 04:08:04 24 4
gpt4 key购买 nike

我对 Rails 还很陌生,目前正在安装 devise gem。

当我创建用户模型并尝试迁移数据库时:

$ 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/migrate 中的迁移文件的副本:

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 还很陌生,所以我实际上很不明白这个错误的含义。我假设我显然已经有一个名为“电子邮件”的列。

另外,我注释掉了 t.string :email 并输入了以下内容:

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`) 

最佳答案

在 Devise 生成的迁移文件中,更改行

t.string:电子邮件,null:false,默认:“”

至:

t.change :email, :string, null: false, 默认值: ""

迁移不是尝试创建新的电子邮件栏,而是将现有电子邮件栏更改为 Devise 的规范

然后运行 ​​rake db:migrate

关于ruby-on-rails - Rails 数据库迁移失败并显示 “duplicate column name: email”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38418844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com