【发布时间】:2013-02-05 04:01:24
【问题描述】:
处理以下类型情况的推荐方法是什么:
假设我有一个名为Cart 的模型,它与模型Person 和相同的PK(用户ID)具有1-1 关系。
在我的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
根据我对异常处理的(有限)知识,我知道不建议以这种方式使用异常,但每次都进行额外的查询值得吗?
【问题讨论】:
标签: ruby-on-rails exception activerecord