Reputation: 337
I am making an app with a shopping cart and have had the shopping cart working for weeks until today when I randomly started to get the following error:
undefined method `title' for nil:NilClass
Extracted source (around line #20):
<%= link_to product.title, product %>
<p><%= number_to_currency(product.price, :unit => '$') %></p>
<p>Quantity: <%= quantity %></p>
I can not figure out why this started to show up and how to fix it.
Here is my code: cart controller:
class CartController < ApplicationController
def add
id = params[:id]
if session[:cart] then
cart = session[:cart]
else
session[:cart] = {}
cart = session[:cart]
end
if cart[id] then
cart[id] = cart[id] + 1
else
cart[id] = 1
end
redirect_to :action => :index end
def clearCart
session[:cart] = nil
redirect_to :action => :index end
def index
if session[:cart] then
@cart = session[:cart]
else
@cart = {}
end end
end
cart/index.html.erb:
<div class="shoping-cart">
<h1>Your Cart</h1>
<% if @cart.empty? %>
<p>Your cart is currently empty</p>
<% else %>
<%= link_to 'Empty Cart', cart_clear_path %>
<% end %>
<br><br><br>
<% total = 0 %>
<div class="list">
<ul>
<% @cart.each do | id, quantity | %>
<% product = Product.find_by_id(id) %>
<li>
<%= link_to product.title, product %>
<p><%= number_to_currency(product.price, :unit => '$') %></p>
<p>Quantity: <%= quantity %></p>
</li>
<% total += quantity * product.price %>
<% end %>
<br><br><br>
<p><p><%= number_to_currency(total, :unit => '$') %></p></p>
</ul>
</div>
<% link_to 'pay now', new_charge_path %>
</div>
Routes:
get '/cart' => 'cart#index'
get '/cart/clear' => 'cart#clearCart'
get '/cart/:id' => 'cart#add'
Upvotes: 1
Views: 52
Reputation: 1176
you need to avoid doing queries inside your views, but, if you want to keep that Product.find_by_id
then you can add a guard class there:
<% @cart.each do | id, quantity | %>
<% product = Product.find_by_id(id) %>
<% if product %>
<li>
<%= link_to product.title, product %>
<p><%= number_to_currency(product.price, :unit => '$') %></p>
<p>Quantity: <%= quantity %></p>
</li>
<% total += quantity * product.price %>
<% end %>
<% end %>
Upvotes: 1