代码之家  ›  专栏  ›  技术社区  ›  andi

是否存在ActiveRecord?或从ActiveRecord中营救::RecordNotFound

  •  17
  • andi  · 技术社区  · 17 年前

    处理以下情况的建议方法是什么:

    Cart ,它与模型具有1-1关系 Person 和相同的PK(用户id)。

    在 index 我的方法 cart_controller 运货马车 为当前用户存在。 如果我这样做 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
    

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

    根据我对exeption处理的(有限的)了解,我知道不建议以这种方式使用异常,但是每次都进行额外的查询是否值得呢?

    4 回复  |  直到 17 年前
        1
  •  34
  •   Oinak    17 年前

    使用按id查找而不是查找:

    @cart = Cart.find_by_id(params[:id])
    

    如果它不存在,则为零,因此您可以根据需要在控制器/视图中检查“if@cart”

        2
  •  23
  •   Baldrick    13 年前

    您可以尝试向用户对象询问其购物车。假设您已将用户分配给 @user 然后,如果用户有购物车,它将是 @user.cart @用户购物车 nil

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

        3
  •  2
  •   danengle    17 年前

    @cart = @user.cart || @user.cart.new
    

    那么在你看来,你可能会有类似。。。

    <% if @cart.empty? # or whatever method you use to determine 
         # if there is nothing in the cart...maybe .blank? is fine? 
    %>
        <p>Your cart is empty</p>
    <% else %>
        <!-- loop through objects in your cart -->
    <% end %>
    
        4
  •  0
  •   John Topley    17 年前

    所以我建议使用异常,它比SQL语句便宜得多。

    推荐文章