When to use `save` vs `save!` in model?
Solution 1:
save!
will raise an error if not successful.
save
will return boolean value like true or false.
Solution 2:
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.
Solution 3:
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.