Я новичок в Rails (я использую Rails 3.0.3), в настоящее время я слежу за книгой «Agile Web Development с Rails», чтобы разработать простое приложение rails.
- создать модель ' Корзина ' класс;
--implement ' add_to_cart ' метод в моем ' store_controller ',
У меня есть строка кода
<%=button_to "Add to Cart", :action => add_to_cart, :id => product %>
в моем / store / index.html.erb
Как видите, :action => add_to_cart
вmy index.html.erb , который вызовет метод add_to_cart
в моем * Controllers / store_controller.rb *
Но после обновления браузера я получил ошибку " неопределенная локальная переменная или метод 'add_to_cart'", по-видимому, у меня есть метод add_to_cart
в моем store_controller.rb, почему я получил эту ошибку ???Какова возможная причина ???
Вот мои коды:
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 %>
Модель / cart.rb
class Cart
attr_reader :items
def initialize
@items = []
end
def add_product(product)
@items << product
end
end