2016-05-08 8 views
1

zeigen nach oben Ich mache eine App mit einem Warenkorb und habe den Warenkorb arbeitet seit Wochen, bis heute habe, als ich die folgende Fehlermeldung erhalten zufällig gestartet:Rails nicht definierte Methode Fehler aus heiterem Himmel

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> 

Ich kann nicht herausfinden, warum das auftauchte und wie ich es beheben konnte.

Hier ist mein Code: Warenkorb 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 

Warenkorb/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> 

Routen:

get '/cart' => 'cart#index' 
    get '/cart/clear' => 'cart#clearCart' 
    get '/cart/:id' => 'cart#add' 

Antwort

1

Sie Rückfragen vermeiden müssen tun innerhalb Ihrer Ansichten, aber wenn Sie diese Product.find_by_id behalten möchten, können Sie eine Schutzklasse t hinzufügen hier:

<% @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 %> 
+0

Das hat perfekt funktioniert, danke für die Hilfe. – Kris

Verwandte Themen