【Rails】Useridがnilになったとき


環境

Rails 6.1.3.1
Ruby 3.0.0
MySQL 8.0.23

エラー内容

Rails consoleで新しいユーザーを作成したときのこと、

irb(main):001:0> User.create(name: "hogege",email: "hoge@hoge",password: "password",password_confirmation: "password")
  TRANSACTION (0.2ms)  BEGIN
  User Exists? (0.7ms)  SELECT 1 AS one FROM `users` WHERE `users`.`email` = 'hoge@hoge' LIMIT 1
  TRANSACTION (0.2ms)  ROLLBACK
=> #<User id: nil, name: "hogege", email: "hoge@hoge", created_at: nil, updated_at: nil, password_digest: [FILTERED]>

Userid, created_at, update_atがnilになってしまいました

+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | bigint       | NO   | PRI | NULL    | auto_increment |
| name            | varchar(255) | YES  |     | NULL    |                |
| email           | varchar(255) | YES  | UNI | NULL    |                |
| created_at      | datetime(6)  | NO   |     | NULL    |                |
| updated_at      | datetime(6)  | NO   |     | NULL    |                |
| password_digest | varchar(255) | YES  |     | NULL    |                |
+-----------------+--------------+------+-----+---------+----------------+

確認してみても、idはauto_increaseになっているので、create!を使ってみる

irb(main):002:0> User.create!(name: "hogege",email: "hoge@hoge",password: "password",password_confirmation: "password")
  TRANSACTION (6.7ms)  BEGIN
  User Exists? (4.3ms)  SELECT 1 AS one FROM `users` WHERE `users`.`email` = 'hoge2@hoge' LIMIT 1
  TRANSACTION (1.9ms)  ROLLBACK
Traceback (most recent call last):
        1: from (irb):7:in `<main>'
ActiveRecord::RecordInvalid (Validation failed: Email is invalid)

なんてことはない話でした。emailの形式が間違っていました、、、

irb(main):008:0> User.create(name: "hogege2",email: "[email protected]",password: "password",password_confirmation: "password")
  TRANSACTION (0.2ms)  BEGIN
  User Exists? (1.5ms)  SELECT 1 AS one FROM `users` WHERE `users`.`email` = '[email protected]' LIMIT 1
  User Create (1.5ms)  INSERT INTO `users` (`name`, `email`, `created_at`, `updated_at`, `password_digest`) VALUES ('hogege2', '[email protected]', '2021-04-11 00:45:14.108385', '2021-04-11 00:45:14.108385', '$2a$12$g5Ks0L4Eiw.QotTeTzt2ieBsTNKBbrpJiNtb6C/JxERBqmus7UD7q')
  TRANSACTION (1.9ms)  COMMIT
=> #<User id: 1, name: "hogege2", email: "[email protected]", created_at: "2021-04-11 00:45:14.108385000 +0000", updated_at: "2021-04-11 00:45:14.108385000 +0000", password_digest: [FILTERED]>

無事成功!

まとめ

create 失敗しているときは何も教えてくれず終わり
create! エラー内容を教えてくれる