文件: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'
代码有什么问题?我使用了一个参考应用来编写我自己的应用程序。