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

前端 未结 3 1679
予麋鹿
予麋鹿 2020-12-23 11:17

According to save bang your head, active record will drive you mad, we should avoid using save! and rescue idiom for exceptional situations. Given

相关标签:
3条回答
  • 2020-12-23 11:37

    save! will raise an error if not successful.

    save will return boolean value like true or false.

    0 讨论(0)
  • 2020-12-23 11:45

    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.

    0 讨论(0)
  • 2020-12-23 11:48

    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.

    0 讨论(0)
提交回复
热议问题