0
0

More than 3 years have passed since last update.

フリマアプリを作成中、キーは取得できているのにデータが保存されない原因が分からなかった。メンターさんに質問したところ原因を探る方法を教えてくれたのでメモ。

save/save!メソッドとは

データを保存するためのメソッド。

saveメソッド

saveメソッドは、保存に成功したらtrueを、保存に失敗(バリデーションに失敗)したらfalseを返す。

save!メソッド

save!メソッドは、保存に成功したらtrueを返すが、保存に失敗(バリデーションに失敗)したら例外が発生します。だから、保存できなかった場合の処理はrescue節で行う必要がある。

■私の場合、binding.pryを使用したところ、キーは取得できていたので、@user.save!を使って原因を探った。
↓保存できなかった時の記述

[8] pry(#<Users::RegistrationsController>)> @user.save!
   (0.2ms)  BEGIN
  ↳ (pry):12
  User Exists (13.4ms)  SELECT  1 AS one FROM `users` WHERE `users`.`email` = BINARY '' LIMIT 1
  ↳ (pry):12
   (1.1ms)  ROLLBACK
  ↳ (pry):12
ActiveRecord::RecordInvalid: Validation failed: Email can't be blank, Email is invalid, Password can't be blank, Nickname can't be blank, Encrypted password can't be blank, Encrypted password is too short (minimum is 7 characters), Encrypted password is invalid, Familyname kanji can't be blank, Familyname kanji is invalid, Firstname kanji can't be blank, Firstname kanji is invalid, Familyname kana can't be blank, Familyname kana is invalid, Firstname kana can't be blank, Firstname kana is invalid, Birthday can't be blank
from /Users/httr_htm/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.4.3/lib/active_record/validations.rb:80:in `raise_validation_error'

ActiveRecord::RecordInvalid以降に原因が書いている。

結果、正規表現の記述が原因だった。emailをaa@aa.aaの形式で設定していたのに、aa@aaと入力していたことにより、バリデーションで引っかかっていた。エラー表示を設定していたらもっと早く解決できたかもしれない。

Rubularという正規表現をチェックするサイトを紹介してもらった。今後、活用していきたい。

参照

Railsのsave!メソッドの使い方を現役エンジニアが解説【初心者向け】

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0