Rails Tutorial: SQLite3::ConstraintException: UNIQUE constraint failed: users.email

巧了我就是萌 提交于 2019-12-03 11:31:19
Ben Muschol

The problem was that I had users in the database with the same email before the migration.

db:reset solved everything

I experienced it for a bit different reason and here is the solution.

For me the error was

Minitest::UnexpectedError: ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: users.email: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2018-05-09 18:23:59.827561', '2018-05-09 18:23:59.827561', 298486374)

Notice the INTO "users" ("created_at", "updated_at", "id"). It was caused by test/fixtures/users.yml was not filled, so then there was duplicate values in columns which has unique key constraint.

test/fixtures/users.yml:

# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value
Moshe Edri

if you can't reset:db you should try to delete it by hand go to db folder and delete the "development.sqlite3" and the "test.sqlite3" files then run rails db:migrate and bin/rails db:migrate RAILS_ENV=TEST

worked for me, anyway...

Just use rake db:test:prepare and it will copy the dev database to test so you don't need to run the migrations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!