積々RUNMIZZO

日々積み重ね

プロフィール更新時のエラー対応

地味に5日目

(メンチキッターにユーザー機能追加中)

ユーザープロフィール編集時に入力内容が反映されずロールバックされる

[1] pry(#<ProfilesController>)> @user
#<User:0x0000000107ad47d0> {
                  :id => 1,
                :name => "test",
               :email => "test@example.com",
    :crypted_password => "$2a$10$4/2YHnQjZ9UaYz6JNNmUG.g0TfERU4MFgOjNLayqtKaZHkZrdkz3u",
                :salt => "D7xFwzvdbdDYBQZy2JUf",
          :created_at => Sun, 23 Jan 2022 22:20:05.190854000 JST +09:00,
          :updated_at => Sun, 23 Jan 2022 22:20:05.190854000 JST +09:00
}
[2] pry(#<ProfilesController>)> user_params
{
     "name" => "test2",
    "email" => "test@example.com"
}
[3] pry(#<ProfilesController>)> @user.update(user_params)
  TRANSACTION (4.2ms)  BEGIN
  ↳ (pry):5:in `update'
  User Exists? (3.2ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 AND "users"."id" != $2 LIMIT $3  [["email", "test@example.com"], ["id", 1], ["LIMIT", 1]]
  ↳ (pry):5:in `update'
  TRANSACTION (2.8ms)  ROLLBACK
  ↳ (pry):5:in `update'
false

エラーメッセージを確認したらパスワード書けよと言われてるけど別に書きたくない

[7] pry(#<ProfilesController>)> @user.errors.messages
{
    :password => ["を入力してください"]
}

モデルに余計な一文があったので削除したら解決◎

validates :password, length: { minimum: 3 }, if: -> { new_record? || changes[:crypted_password] }
validates :password, confirmation: true, if: -> { new_record? || changes[:crypted_password] }
validates :password_confirmation, presence: true, if: -> { new_record? || changes[:crypted_password] }

validates :email, uniqueness: true, presence: true
validates :password, presence: true  # <= コイツ要らんかった
validates :name, presence: true, length: { maximum: 255 }