0

我的应用程序似乎在本地运行良好。我所有的代码似乎都是正确的。我的错误是告诉我它找不到记录。

我有一个名为购物车的模型,它通过会话变量与用户相关,我使用 current_cart 辅助方法将用户与他们的购物车相关联。我的错误和代码如下:

错误

2013-07-14T23:53:08.615652+00:00 heroku[web.1]: State changed from starting to up
2013-07-14T23:53:09.480513+00:00 app[web.1]: Started GET "/" for 108.2.221.210 at 2013-07-14 23:53:09 +0000
2013-07-14T23:53:09.514335+00:00 app[web.1]: Processing by ProductsController#index as HTML
2013-07-14T23:53:09.622655+00:00 app[web.1]: Completed 404 Not Found in 108ms
2013-07-14T23:53:09.624409+00:00 app[web.1]: 
2013-07-14T23:53:09.624409+00:00 app[web.1]:   app/controllers/products_controller.rb:6:in `index'
2013-07-14T23:53:09.624409+00:00 app[web.1]:   app/controllers/application_controller.rb:20:in `current_cart'
2013-07-14T23:53:09.624409+00:00 app[web.1]: 
2013-07-14T23:53:09.624409+00:00 app[web.1]: 
2013-07-14T23:53:09.624409+00:00 app[web.1]: ActiveRecord::RecordNotFound (Couldn't find Cart with id=1):
2013-07-14T23:53:09.627892+00:00 heroku[router]: at=info method=GET path=/ host=pxdirect.herokuapp.com fwd="108.2.221.210" dyno=web.1 connect=1ms service=149ms status=404 bytes=728
2013-07-14T23:53:09.777019+00:00 heroku[router]: at=info method=GET path=/favicon.ico host=pxdirect.herokuapp.com fwd="108.2.221.210" dyno=web.1 connect=1ms service=10ms status=200 bytes=0

产品控制器

  def index
          @products = Product.search(params)
      unless current_cart.nil?
          @cart = current_cart
      else
          @cart = nil
      end
  end

索引视图

 <% unless @cart.nil? %>
      <% if @cart.total_quantity > 0 %>
          <b>Cart&nbsp;(<%=@cart.total_quantity%>&nbsp;items)&nbsp;</b><i class="icon-shopping-cart"></i>
      <% else %>
          <b>Cart&nbsp;</b><i class="icon-shopping-cart"></i>
      <% end %>
 <% else %>
      <b>Cart&nbsp;</b><i class="icon-shopping-cart"></i>
 <% end %>

应用控制器

def current_cart
    if session[:cart_id]
          @current_cart ||= Cart.find(session[:cart_id])
          session[:cart_id] = nil if @current_cart.purchased_at
    end
    if session[:cart_id].nil?
      @current_cart = Cart.create!
      session[:cart_id] = @current_cart.id
    end
    @current_cart
  end

任何见解表示赞赏

4

1 回答 1

2

我想你必须处理ActiveRecord::RecordNotFound错误:

def current_cart

  if session[:cart_id]
    begin
      @current_cart ||= Cart.find(session[:cart_id])
      session[:cart_id] = nil if @current_cart.purchased_at
    rescue ActiveRecord::RecordNotFound => e
      create_cart
    end
  else
    create_cart
  end

  @current_cart
end

def create_cart
  @current_cart = Cart.create!
  session[:cart_id] = @current_cart.id
end

这可能是由无效的会话数据引起的。

于 2013-07-15T03:18:50.793 回答