link_to的不需要的行为

时间:2016-04-17 05:53:42

标签: ruby-on-rails-4

文件:shopping_carts_controller.rb

class ShoppingCartsController < ApplicationController
    before_filter :extract_shopping_cart

    def create
        @product = Product.find(params[:product_id])
        @shopping_cart.add(@product, @product.price)
        redirect_to shopping_cart_path
    end

    def show

    end

   private
       def extract_shopping_cart
           shopping_cart_id = session[:shopping_cart_id]
           @shopping_cart = session[:shopping_cart_id] ?    ShoppingCart.find(shopping_cart_id) : ShoppingCart.create
           session[:shopping_cart_id] = @shopping_cart.id
       end
   end

在app / views / products / index.html.erb

<%= link_to 'Add to cart', shopping_cart_path(product.id), :method => 'POST', :class=>"btn btn-success" %>                    

正在生成

http://localhost:3001/shopping_cart.1 link 

显示错误

ActiveRecord::RecordNotFound at /shopping_cart.1
Couldn't find Product with 'id'=

在routes.rb

resource :shopping_cart
resources :products

devise_for :users, path_names: { sign_in: 'login', sign_out: 'logout' },
                 controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }

root to: 'welcome#index'

代码有什么问题?我使用了一个参考应用来编写我自己的应用程序。

2 个答案:

答案 0 :(得分:0)

你是错误的&#39;在资源

答案 1 :(得分:0)

您需要将路线配置为:

resources :shopping_cart

哪个给出 enter image description here

如果只添加resource :shopping_cart,则会提供以下路线: enter image description here

相关问题