Reputation: 246
My application seems to be running fine locally. All of my code seems correct. My error is telling me that it could not find a record.
I have a model called cart which is related to users through session variables, I use the current_cart helper method to relate users to their carts. My error and code is below:
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 (<%[email protected]_quantity%> items) </b><i class="icon-shopping-cart"></i>
<% else %>
<b>Cart </b><i class="icon-shopping-cart"></i>
<% end %>
<% else %>
<b>Cart </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
Any insight is appreciated
Upvotes: 0
Views: 137
Reputation: 21795
I suppose you have to handle ActiveRecord::RecordNotFound
error:
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
This could be caused by invalid session data.
Upvotes: 2