Heroku中的错误没有意义,应用程序在本地运行正常。记录不存在

时间:2013-07-15 00:06:16

标签: ruby-on-rails heroku conditional helpers production

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

我有一个名为cart的模型,它通过会话变量与用户相关,我使用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 %>

的ApplicationController

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

赞赏任何见解

1 个答案:

答案 0 :(得分:1)

我想你必须处理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

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