Rails form won't submit self-referential form
I have a form that adds a product to the cart. It's a simple form that sends a POST request to /products/1/add_to_cart
It all works well when I'm on the /products/1 page and I'm submitting t开发者_如何学Che form to add the product to the cart. It doesn't, however, work when I've added the product to the cart and then try to add it again. I get a 'no route matches "/products/1/add_to_cart"' error.
When submitting the form from /products/1, it succeeds and the logs show:
Started POST "/products/1/add_to_cart" for 127.0.0.1 at 2011-07-04 16:10:27 -0600
Processing by ProductsController#add_to_cart as HTML
After this request, the item has been added to the cart and the controller action calls a render :action => 'show' (to keep the validation errors of adding the item to the cart). The URL is now /products/1/add_to_cart
When trying to submit the form again (from /products/1/add_to_cart) to add the item to the cart a second time, I get a routing Error:
Started POST "/products/1/add_to_cart" for 127.0.0.1 at 2011-07-04 16:13:05 -0600 ActionController::RoutingError (No route matches "/products/1/add_to_cart"):
Am I missing something here? Why won't Rails find the route if I'm submitting the form from the URL the form will be processed by (ie: /products/1/add_to_cart submits a form to /products/1/add_to_cart)?
-----UPDATE------
Per-request, here is the related route:
resource :store, :only => [:show], :controller => 'Store' do
resources :products, :except => [:index], :shallow => true do
member do
post :add_to_cart
end
end
end
Here is the (slimmed down) controller:
class ProductsController < ApplicationController
def show
@cart_item = CartItem.new
end
def add_to_cart
@product = Product.find(params[:id])
@cart_item = CartItem.new(params[:cart_item])
@cart_item.product = @product
if @cart_item.save
current_cart.items << @cart_item
flash[:notice] = 'This item was added to your cart.'
end
render :action => :show
end
end
精彩评论