What exactly saves / saves! make?

I noticed that the general line for checking errors in rails is:

if @user.save! 

not something like

 Save If Save is successful Blah Else Blah End 

So my understanding is "if @ user.save!" lies in the fact that it saves the object and returns true / false if it was successful. If I call it later, for example:

 @user.save! if @user.save! blah end 

Am I executing a save request twice?

+3
source share
1 answer

A small difference, I admit, but nonetheless important. The dock here is good enough:

save!

Saved! checks are always performed. If any of these fail ActiveRecord :: RecordInvalid gets promoted.

save (perform_validation = true)

if perform_validation true verification is performed. If any of them does not work, the action is canceled, and the save returns false. If the flag is false, then checks are completely excluded. For more information, see ActiveRecord :: Validations.

So, with the exception! not just return true or false, but only return to success and raise an excpetion if it fails.

The purpose of this difference is that with save !, you can catch errors in your controller using standard ruby ​​tools for this, while save allows you to do the same with standard if-clauses. At least that's what I think.

+7
source

Source: https://habr.com/ru/post/1343297/


All Articles