2019/05/07
問題発生
Rails チュートリアルの6章の「メールアドレスの一意性を強制するためのマイグレーション」する箇所でマイグレートションができなかった。
Admin:~/environment/sample_app (modeling-users) $ rails db:migrate
== 20190507235118 AddIndexToUsersEmail: migrating =============================
-- add_index(:users, :email, {:unique=>true})
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::BusyException: database is locked: CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")
解決策
SQLite3::BusyException: database is locked
はデータベースがロックされているという意味。マイグレーションする少し前にRailsコンソールでuserオブジェクトを作成する箇所があり、そこでデータベースがロックされてしまうらしい。コンソールからexit
したら解決した。
Admin:~/environment/sample_app (modeling-users) $ rails console --sandbox
Running via Spring preloader in process 7572
Loading development environment in sandbox (Rails 5.1.6)
Any modifications you make will be rolled back on exit
>> user = User.create(name: "Example User", email: "user@example.com")
(0.1ms) SAVEPOINT active_record_1
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) LIMIT ? [["email", "user@example.com"], ["LIMIT", 1]]
SQL (1.4ms) INSERT INTO "users" ("name", "email", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "Example User"], ["email", "user@example.com"], ["created_at", "2019-05-08 00:15:31.209002"], ["updated_at", "2019-05-08 00:15:31.209002"]]
(0.1ms) RELEASE SAVEPOINT active_record_1
=> #<User id: 1, name: "Example User", email: "user@example.com", created_at: "2019-05-08 00:15:31", updated_at: "2019-05-08 00:15:31">
>> user.email.upcase
=> "USER@EXAMPLE.COM"
>> duplicate_user = user.dup
=> #<User id: nil, name: "Example User", email: "user@example.com", created_at: nil, updated_at: nil>
>> duplicate_user.email = user.email.upcase
=> "USER@EXAMPLE.COM"
>> duplicate_user.valid?
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) LIMIT ? [["email", "USER@EXAMPLE.COM"], ["LIMIT", 1]]
=> false
>> exit
(0.2ms) rollback transaction