Newbie question: undefined local variable or method , why??
Posted
by
Mellon
on Stack Overflow
See other posts from Stack Overflow
or by Mellon
Published on 2010-12-30T12:51:12Z
Indexed on
2010/12/30
12:54 UTC
Read the original article
Hit count: 296
ruby-on-rails
|ruby-on-rails3
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
© Stack Overflow or respective owner