何时在模型中使用 `save` 和 `save!`? [英] When to use `save` vs `save!` in model?

查看:37
本文介绍了何时在模型中使用 `save` 和 `save!`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 save bang your head, active record 会让你发疯,我们应该避免在特殊情况下使用 save!rescue 习语.鉴于此,假设模型需要 @post.mark_rejected.

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.

如果 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:

  • 控制器动作必须检查 mark_rejected 的返回值并执行它
  • 我们不希望该方法调用出现异常,因此我们没有在控制器操作中编写 rescue 子句,因此异常冒泡到 (..wherever..) 并且可能会显示为一些(500 HTTP?)错误
  • controller action would have to check for return value of mark_rejected and do it's thing
  • we are not expecting an exception from that method call, so we do not write a rescue clause in the controller action, thus the exception bubbles up to (..wherever..) and will probably show up as some (500 HTTP?) error

示例代码:

def mark_rejected
  ...
  save!
end

def mark_rejected
  ...
  save
end

推荐答案

异常有更多的开销,因此存在性能问题,尤其是当可以预期它可能会经常抛出时,例如保存.

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.

检查返回值是否为 false 的代码行比拯救异常要少,所以我不明白如果你已经必须拯救异常,必须检查返回值有什么问题.在实践中,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.

如果在调用 save 而不是 save! 时抛出异常,您应该希望它显示 500 错误页面,因为这就是发生的情况:不可恢复的、未知的, 意外的内部服务器错误.

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.

这篇关于何时在模型中使用 `save` 和 `save!`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆