1

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'

1 Answer 1

1

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 %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.