ActiveRecord的#存在?或从ActiveRecord :: RecordNotFound救援

and*_*ndi 17 activerecord ruby-on-rails exception

处理以下类型情况的推荐方法是什么:

假设我有一个名为的模型Cart,它与模型具有1-1关系,Person并且具有相同的PK(用户的id).

index我的方法中,我cart_controller想检查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
Run Code Online (Sandbox Code Playgroud)

2.使用ActiveRecord#存在?方法

 if Cart.exists?(the_user_id)
    @cart = Cart.find(the_user_id)
    #more code here
 else
    #the cart is empty message
 end
Run Code Online (Sandbox Code Playgroud)

从我(有限的)关于exeption处理的知识我知道不建议以这种方式使用异常,但每次都值得进行额外的查询吗?

Oin*_*nak 34

使用find_by_id而不是find:

@cart = Cart.find_by_id(params[:id])
Run Code Online (Sandbox Code Playgroud)

nil如果它不存在,那么你可以根据需要检查控制器/视图中的"if @cart"


Lee*_*ing 23

您可以尝试向用户对象询问其购物车.假设您已经分配了用户,@user那么如果用户有购物车,那么就是这样@user.cart.如果@user.cart是,nil那么他们就没有.

这假设您正确设置了模型之间的关系.