【问题标题】:Newbie question: undefined local variable or method , why?新手问题:未定义的局部变量或方法,为什么?
【发布时间】: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


    【解决方案1】:

    在尝试创建 Rails3 应用程序时,您似乎正在阅读本书的旧版本(使用 Rails 2 编写)。

    要简单地添加您需要的路线,请添加

    match 'store/add_to_cart/:id' => 'store#add_to_cart'
    

    了解 RESTful 应用程序涉及更多内容。基本上,你设计你的应用程序,使它由几个资源组成,你可以创建、更新、删除、链接等。

    我强烈建议选择基于 Rails3 的“Agile Web Development with Rails”的最新版本。它会为您解决问题(特别是,您将在第 124 页看到,以 RESTful 方式将商品添加到购物车的管理方式不同)。

    【讨论】:

    • 同意使用新书。在阅读 Rails 2 的同时尝试学习 Rails 3 最多只会适得其反。
    【解决方案2】:

    我通过取消注释解决了我的问题

    # This is a legacy wild controller route that's not recommended for RESTful applications.
    # Note: This route will make all actions in every controller accessible via GET requests.
       match ':controller(/:action(/:id(.:format)))'
    

    配置/routes.rb

    那我还有一个问题想问一下,正如上面的配置所说,取消命令行RESTful应用不推荐,那么RESTful应用解决这个问题的方法是什么?? ?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-16
      • 2017-01-26
      • 1970-01-01
      • 2018-04-19
      • 2015-01-01
      相关资源
      最近更新 更多