开发者

Rails 3 - Nested Resources - Routing

I'm having issues with my destroy method on a nested source Product, that is tied to Orders.

After attempting to destroy an item, I'm redirecting users to my order_products_url. I receive the following routing error:

No route matches "/orders/1/products"

My destroy method looks like this:

def destroy
    @product = Product.find(params[开发者_运维技巧:id])
    @order = Order.find(params[:order_id])
    @product.destroy

    respond_to do |format|
      format.html { redirect_to(order_products_url) }
      format.xml  { head :ok }
    end
end

And in routes.rb:

resources :orders do
    resources :products, :controller => "products"    
  end

The reason why this is confusing me, is for my update method for products, I'm properly redirecting users to the order_products_url without issue. I don't understand why it works there but not here.

Thanks


order_products_url expects a parameter to be passed - either the order id, or the order object itself. Without this, it won't work properly. So using your code above:

def destroy
    @product = Product.find(params[:id])
    @order = Order.find(params[:order_id])
    @product.destroy

    respond_to do |format|
      format.html { redirect_to(order_products_url(@order) }
      format.xml  { head :ok }
    end
end

As a side note, you can shorten your routes a little:

resources :orders do
  resources :products
end

Specifying the controller is redundant when it's named as Rails expects. I hope this helps!

UPDATE: I've added a link to my article about routing in Rails 3, with downloadable code samples. I updated it with a paragraph that explains named routes, in the "Things You Should Know" section:

Routing in Ruby on Rails 3


Don't you need to redirect to order_products_url(@order)?


you should be using orer_products_path (not url). If you go to the root of your app and type,

rake routes

that will give you a list of all named routes. You need to append _path to them though (returns the string representation). This is a handy little trick for figuring out named routes.

Now to your real question - of course it doesn't exist! You just deleted it! You are destroying the product instead of the product from the order!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜