Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does save/save! do?

I've noticed that a common error check line in rails is:

if @user.save!

rather than something like

Save
If Save is successful
 Blah
Else
 Blah
End

So my understanding of "if @user.save!" is that it both saves the object and returns true/false if it was successful. If I call it later on, such as:

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

Am I executing the save query twice?

like image 215
Kevin Avatar asked Jan 04 '10 02:01

Kevin


1 Answers

A little difference, I admit, but nevertheless, important. The documentation is quite good here:

save!

With save! validations always run. If any of them fail ActiveRecord::RecordInvalid gets raised.

save(perform_validation=true)

if perform_validation is true validations run. If any of them fail the action is cancelled and save returns false. If the flag is false validations are bypassed altogether. See ActiveRecord::Validations for more information.

So, save! won't just return true or false but only true on success and raise an excpetion if it fails.

The purpose of this distinction is that with save!, you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.

like image 130
moritz Avatar answered Oct 29 '22 08:10

moritz