【发布时间】:2010-12-31 03:40:35
【问题描述】:
我是 Rails 新手(我使用的是 Rails 3.0.3),目前我正在按照《Agile Web Development with Rails》一书开发一个简单的 Rails 应用程序。
我跟着这本书去:
--创建模型'Cart'类;
--在我的“store_controller”中实现“add_to_cart”方法,
我有一行代码<%=button_to "Add to Cart", :action => add_to_cart, :id => product %>
在我的 /store/index.html.erb
如您所见,我的index.html.erb中有:action => add_to_cart,它将调用我的*Controllers/store_controller.rb*中的add_to_cart方法
但是刷新浏览器后,我得到了错误“未定义的局部变量或方法'add_to_cart'”,显然我的'store_controller.rb'中有add_to_cart的方法,为什么我收到这个错误???可能的原因是什么???
这是我的代码:
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
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3