Rails: Is there a way to make nested resources work automatically with `link_to`?

I have a rails application with nested resources, for example:

resources :product do
  resources :sales
end

Where Sale belongs_to Product, and a copy Salecannot exist without a product.

I can use link_to+ @productto directly link to the product:

<%= link_to @product.name, @product %>

It creates

<a href="/products/3">Strawberry Jam</a>

If I want to do something like this for sale, I cannot use it only @sale. I have to use the product. This will not work:

<%= link_to @sale.date, @sale %>

I should use something like this:

<%= link_to @sale.date, [@sale.product, @sale] %>

The first case will not work, because it is sale_pathnot defined (only product_sale_paththere is).

My question is: can I add something to the Sale model so that link_to(or url_for) automatically adds the "parent" (the product in this case) when creating the URL?

url_for, , monkeypatching HelperMethodBuilder.url.handle_model_call, , .

+4
3

, URL- ?

resources :products do
  resources :sales, only: [:index, :new, :create]
end
resources :sales, only: [:show, :edit, :update, :destroy]

link_to @sale , index, new, create.

http://guides.rubyonrails.org/routing.html#nested-resources ( )

+2

:

resources :product do
  resources :sales, shallow: true
end

2.7.2 Rails.

+2

link_to @sale.date product_sale_path(@sale.product, @sale)

link_to @sale.date product_sale_path(@sale.product_id, @sale)

/products/:product_id/sales/:id.

I assume that a product may have more than one sale. To reference an index action, you only need a product.

link_to product_sales_path(@sale.product)

+1
source

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


All Articles