Zabba
Zabba

Reputation: 65497

When to use `save` vs `save!` in model?

According to save bang your head, active record will drive you mad, we should avoid using save! and rescue idiom for exceptional situations. Given that, say a model needs to @post.mark_rejected.

If the code in mark_rejected fails due to one of the below problems, should an exception be thrown? :

If we do not throw an exception, then:

Example code:

def mark_rejected
  ...
  save!
end

or

def mark_rejected
  ...
  save
end

Upvotes: 86

Views: 98215

Answers (3)

gamliela
gamliela

Reputation: 4099

Suggestion: use save when it's on the last line; save! otherwise.

The idea: if the method is returning the save's result you should not throw exception and let the caller to handle save problems, but if the save is buried inside model method logic you would want to abort the process with an exception in case of failure.

Upvotes: 11

Selvamani
Selvamani

Reputation: 7684

save! will raise an error if not successful.

save will return boolean value like true or false.

Upvotes: 215

Andrew Marshall
Andrew Marshall

Reputation: 96994

There's more overhead in an exception, so there is a performance issue, especially when it can be expected that it will likely be thrown often, as is the case with save.

It is fewer lines of code to check if the return value is false than rescue an exception, so I don't see how it's a problem having to check for the return value if you already have to rescue the exception. How often would an exception thrown by save! ever have to bubble-up the call stack in practice? Rarely, if ever, in my experience.

If there is an exception thrown when calling save as opposed to save! you should want it to show a 500 error page because that's what happened: an unrecoverable, unknown, unexpected internal server error.

Upvotes: 27

Related Questions