Я делаю приложение, с корзиной и был корзина работает в течение нескольких недель до сегодняшнего дня, когда я случайно начал получать следующее сообщение об ошибке:Rails Неопределенного метод ошибка появляется из голубой
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'
Это получилось отлично, спасибо за помощь. – Kris