新手问题 ActionController::UrlGenerationError 怎么解决?

wangyzyoga · January 23, 2015 · Last by heylonj replied at January 23, 2015 · 2296 hits

为了添加购物车功能,增加如下代码后,访问http://xx.xx.xx.xx:8080/store/index老提示截图错误: 是不是因为 routes 中未做配置?需要如何正确配置?

models/cart.rb
```ruby
class Cart
    attr_reader :items
  def initialize
        @items = []
    end
    def add_product(product)
        @items << product
    end
end

views/store/index.html.erb中增加:

<%= button_to "Add to Cart", :action => 'add_to_cart', :id => product  %>

controllers/store_controller.rb

class StoreController < ApplicationController
  def index
    @products = Product.find_products_for_sale
  end
  def add_to_cart
    @cart = find_cart
    product = Product.find(params[:id])
    # @product = Product.where(:id => params[:id]).first
    @cart.add_product(product)
    end
private
  def find_cart
    session[:cart] ||= Cart.new
  end
end
resources :store, only: :index do
  match :add_to_cart, via: :post, on: :member, via: :post  #添加购物车一般用post
end
You need to Sign in before reply, if you don't have an account, please Sign up first.