When to use `save` vs` save! `In the model?

According to save the header, an active recording will infuriate you , we should avoid using save! and rescue idioms for exceptional situations. Given that the model requires @post.mark_rejected .

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

  • if there is a verification problem
  • if a non-nullable field is set to null
  • if there was a loss of communication in the database

If we do not throw an exception, then:

  • Controller actions should check the return value of mark_rejected and do this.
  • we do not expect an exception from this method call, therefore we do not write a rescue clause in the controller action, therefore the exception is bubbling up to (anywhere) and will probably be displayed as part (500 HTTP?)

Code example:

 def mark_rejected ... save! end 

or

 def mark_rejected ... save end 
+44
ruby-on-rails-3
Feb 20 '11 at 10:16
source share
2 answers

The exception has more overhead, so there is a performance problem, especially when you can expect that it will most likely be selected often, as is the case with save .

Fewer lines of code checks to see if the return value is false than the crash exception, so I don't see how this is a problem with checking the return value if you already need to save the exception. How often is the exception thrown by save! ever had to pick up a call stack in practice? Rarely, if ever, in my experience.

If, when calling save an exception exists, not save! , you need it to display a page with an error of 500 because what happened is what happened: an error that has not been repaired is unknown and unexpected.

+18
Feb 20 '11 at 10:27
source share

save! will result in an error if it fails.

save will return true or false.

+92
Dec 11 '14 at 11:26
source share



All Articles