Newbie question: undefined local variable or method , why??
- by Mellon
I am new in Rails (I am using Rails 3.0.3), currently I am following the book "Agile Web Development with Rails" to develop a simple rails application.
I followed the book to:
--create a model 'Cart' class;
--implement 'add_to_cart' method in my 'store_controller', 
I have a line of code
<%=button_to "Add to Cart", :action => add_to_cart,  :id => product %> 
in my /store/index.html.erb
As you see, there is :action => add_to_cart in my index.html.erb, which will invoke the add_to_cart method in my *Controllers/store_controller.rb*
But after I refresh the browser, I got the error "undefined local variable or method 'add_to_cart'", apparently I do have the method add_to_cart in my 'store_controller.rb', why I got this error??? What is the possible cause???
Here are my codes:
store_controller.rb
    class StoreController < ApplicationController
      def index
        @products = Product.find_products_for_sale
      end
      def add_to_cart
        product = Product.find(params[:id]) 
        @cart = find_cart                   
        @cart.add_product(product)          
      end
    private
      def find_cart
        session[:cart] ||= Cart.new
      end
    end
/store/index.html.erb
<h1>Your Pragmatic Catalog</h1>
<% @products.each do |product| -%>
  <div class="entry">
    <%= image_tag(product.image_url) %>
    <h3><%=h product.title %></h3>
    <%= product.description %>
    <div class="price-line">
    <span class="price"><%= number_to_currency(product.price) %></span>
    <!-- START_HIGHLIGHT -->
    <!-- START:add_to_cart -->
    **<%= button_to 'Add to Cart', :action => 'add_to_cart', :id => product %>**
    <!-- END:add_to_cart -->
    <!-- END_HIGHLIGHT -->
    </div>
  </div>
<% end %>
Model/cart.rb
class Cart
  attr_reader :items   
  def initialize
    @items = []
  end
  def add_product(product)
    @items << product
  end
end