Kevin
Kevin

Reputation: 1120

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?

Upvotes: 5

Views: 7116

Answers (1)

moritz
moritz

Reputation: 2478

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.

Upvotes: 8

Related Questions