如果失败,`update_attribute`会返回什么?

Sal*_*lil 5 ruby ruby-on-rails update-attributes 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
Run Code Online (Sandbox Code Playgroud)

有没有机会Line 44失败?因为数据库内存已满或网络出现故障.在那种情况下会发生什么?如果这会产生问题,那么避免它的更好方法是什么?update_attribute失败后会返回什么?

mik*_*kej 5

以下是来源update_attribute:

def update_attribute(name, value)
  send(name.to_s + '=', value)
  save(false)
end
Run Code Online (Sandbox Code Playgroud)

您可以看到它更新了所请求的属性,然后使用set to 调用save.因此,如果任何保存回调(例如)阻止通过返回保存记录,则返回.perform_validationsfalseupdate_attributefalsebefore_savefalse

如果存在较低级别的错误,例如数据库中的内存不足,那么我希望数据库驱动程序将此作为异常提升,这将被传递给您的代码.


Abo*_*uby 1

如果 update_attributes 失败,将返回 false。如果您忽略返回值,您也不会知道它发生了。您可以使用 update_attributes!,它又调用 save!,如果出现问题,它又会引发异常。虽然这是你不能错过的事情(除非你编写了包罗万象的救援语句),但如果你没有抓住它,它就会落入Rails,并且它将中止请求。

检查返回值通常是个好主意。