我正在使用购物车制作应用程序并让购物车工作数周,直到今天我随机开始出现以下错误:
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>
我无法弄清楚为什么会出现这种情况以及如何解决它。
这是我的代码: 推车控制器:
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
车/ 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>
路线:
get '/cart' => 'cart#index'
get '/cart/clear' => 'cart#clearCart'
get '/cart/:id' => 'cart#add'
答案 0 :(得分:1)
您需要避免在视图中进行查询,但是,如果您想保留Product.find_by_id
,那么您可以在那里添加一个保护类:
<% @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 %>