如果 update_attribute 失败,会返回什么?
我有以下代码
@user = User.find(params[:id])
if (@user.activation_status == "active")
#some code here
@user.update_attribute('activation_status' ,'inactive') # Line 44
#send mail to user that his account is Acivated
else
end
Line 44
是否有可能失败?因为数据库内存已满或者网络故障。那样的话会发生什么?如果这会产生问题,有什么更好的方法可以避免它?如果失败,update_attribute
返回什么?
I have following piece of code
@user = User.find(params[:id])
if (@user.activation_status == "active")
#some code here
@user.update_attribute('activation_status' ,'inactive') # Line 44
#send mail to user that his account is Acivated
else
end
Is there any chance that Line 44
could fail? Because database memory is full or network failure. What will happen in that case? If that creates a problem, what is a better way to avoid it? What does update_attribute
return if it failed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是
update_attribute
的来源:您可以看到它更新了请求的属性,然后调用 保存,并将
perform_validations
设置为false
。因此,如果任何保存回调(例如before_save
)通过返回false
阻止记录保存,update_attribute
将返回false
代码>.如果存在较低级别的错误,例如数据库内存不足,那么我希望数据库驱动程序将其作为异常引发,并将其传递给您的代码。
Here is the source for
update_attribute
:You can see that it updates the requested attribute and then calls save with
perform_validations
set tofalse
. Thereforeupdate_attribute
would returnfalse
if any of the save callbacks (e.g.before_save
) prevented the record from being saved by returningfalse
.If there was a lower level error such as out of memory at the database then I expect the database driver to raise this as an exception which would be passed up to your code.
如果 update_attributes 失败,将返回 false。如果您忽略返回值,您也不会知道它发生了。您可以使用 update_attributes!,它又调用 save!,如果出现问题,它又会引发异常。虽然这是你不能错过的事情(除非你编写了包罗万象的救援语句),但如果你没有抓住它,它就会落入Rails,并且它将中止请求。
检查返回值通常是个好主意。
If update_attributes fails, it will return false. if you ignore the return value, you'll have no idea it happened either. You can use update_attributes!, which in turn calls save!, which in turn raises an exception if something goes wrong. While this is something you can't miss (unless you write catch-all rescue statements), if you don't catch it, it will fall through to Rails, and it will abort the request.
It's usually a good idea to check the return value.