[Ruby] save! method

1 minute read

While creating the flea market app, I did not understand the reason why the data was not saved even though the key was acquired. When I asked the mentor, he told me how to find out the cause, so take a note.

What is the #save/save! method? A method for saving data.

save method

The save method returns true if the save was successful and false if the save failed (failed validation).

save! method

The save! method returns true if the save is successful, but raises an exception if the save fails (validation fails). Therefore, if it cannot be saved, it is necessary to perform processing in the rescue section.

■In my case, when I used binding.pry, the key could be obtained, so I searched for the cause using @user.save!. ↓Description when it could not be saved

[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'

The cause is written after ActiveRecord::RecordInvalid.

As a result, the description of the regular expression was the cause. The email was set in the format of [email protected], but the input was [email protected], so it was caught in the validation. If the error display was set, it might have been solved earlier.

I was introduced to a site called Rubular that checks regular expressions. I would like to utilize it in the future.

See #### Active engineers explain how to use save! method of Rails [for beginners]