Rails 3 - Nested Resources - Routing

I am having problems with my destroy method on a nested source product that is bound to Orders.

After trying to destroy the item, I redirect users to my order_products_url. I get the following routing error:

No route matches "/orders/1/products"

My destruction method is as follows:

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 this confuses me is my update method for products, I am redirecting users to order_products_url correctly without any problems. I do not understand why he works there, but not here.

thank

+3
source share
3 answers

order_products_url , - , . . , :

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

:

resources :orders do
  resources :products
end

, Rails. , !

UPDATE: Rails 3 . , , ", ":

Ruby on Rails 3

+8

order_products_url (@order)?

+3

orer_products_path ( url). ,

rake routes

which will provide you with a list of all named routes. You need to add _path to them (returns a string representation). This is a handy little trick for defining named routes.

Now to your real question - of course, it does not exist! You just deleted it! You destroy the product instead of the product from the order!

+1
source

Source: https://habr.com/ru/post/1779465/


All Articles