处理以下类型情况的建议方法是什么:
假设我有一个名为 Cart
的模型,它与模型 Person
具有 1-1 关系,并且具有相同的 PK(用户的 id)。
在我的cart_controller
的index
方法中,我想检查当前用户是否存在Cart
。
如果我执行 Cart.find(the_user_id)
并且购物车不存在,则会引发 RecordNotFound
异常。
我看到有两种解决这个问题的方法:
1。从异常中拯救
begin
@cart = Cart.find(the_user_id)
#more code here
rescue ActiveRecord::RecordNotFound
#the cart is empty message
end
2。使用 ActiveRecord#exists?方法
if Cart.exists?(the_user_id)
@cart = Cart.find(the_user_id)
#more code here
else
#the cart is empty message
end
根据我对异常处理的(有限)知识,我知道不建议以这种方式使用异常,但是每次都进行额外的查询值得吗?
最佳答案
使用 find_by_id 而不是查找:
@cart = Cart.find_by_id(params[:id])
如果不存在则为 nil,因此您可以根据需要在 Controller / View 中检查“if @cart”
关于ruby-on-rails - ActiveRecord#存在吗?或从 ActiveRecord::RecordNotFound 中救援,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/896991/