Generic-user-small Jacob Lichner 2 posts

around pages 108-110 (pdf), I have written the code for the shopping cart, but when I push the ‘add to cart’ button I get a ‘NoMethodError in StoreController#add_to_cart’ and that I have a nil object when I didn’t expect it…

I have the method in the StoreController and everything is exactly what is written in the book…

would anybody care to help me out?

 
Generic-user-small Don Bessinger 9 posts

Without seeing your code, I’d say to check and make sure that your add_to_cart definition in app/controllers/store_controller.rb is in the public section. In other words, make sure your definition isn’t below the “private” keyword (assuming you’ve added it to hide the find_cart definition).

If that doesn’t help, it would make it easier to see what’s going on if I (or someone who actually knows what they’re doing) could see your code for these files:

app/models/cart.rb
app/controllers/store_controller.rb
app/views/store/index.rhtml

 
Generic-user-small theodore nor... 1 post

I’m having the same problem

Any help would be greatly appreciated.

cart.rb -


class Cart
  attr_reader :items

  def initialize
    @items = []
  end

  def add_product(product)
    @items << product
  end
end

store_controller.rb


class StoreController < ApplicationController

  def index
    @products = Product.find_products_for_sale
  end

  def add_to_cart
    @cart = find_cart
    product = Product.find(params[:id])
    @card.add_product(product)
  end

  private

  def find_cart
    session[:cart] ||= Cart.new
  end

end

index.rhtml -


<h1>Your Pragmatic Catalog</h1>

<% for product in @products -%>
  <div class = "entry">
    <img src = "<%= product.image_url %>"/>
    <h3><%= h(product.title) %></h3>
    <%= product.description %>
    <span class = "price">
      <%= number_to_currency(product.price) %>
    </span>
    <%= button_to "Add to Cart",
                  :action => :add_to_cart,
                  :id => product %>
  </div>
<% end %>
 
Generic-user-small Thomas von S... 1 post

Hi Theodore,

In your store_controller.rb you have a typo:

current: @card.add_product(product)
better: @cart.add_product(product)

Thomas

4 posts, 4 voices