[RUBY] What's happening with routing nesting

Operating environment Ruby 2.6.5 Rails 6.0.3.2

It was hard to see what was happening due to the routing nesting, so I posted it for my own confirmation.

When routing is nested

routes.rb


Rails.application.routes.draw do
  resources :hoges do
    resources :fugas, only: [:index]
  end
end

In the above code, fugas is nested for hoges, and when I run rails routes on the terminal, it looks like this:

Prefix ➡︎ hoge_fugas Verb ➡︎ GET URI Pattern ➡︎ /hoges/:hoge_id/fugas(.:format) Controller#Action ➡︎ fugas#index

Of course, other than the above is also displayed, but this time only the nested part will be dealt with. It's hard to understand with just this, so let's compare it with the case where the routing is not nested.

If you do not want to nest routes

routes.rb


Rails.application.routes.draw do
  resources :hoges
  resources :fugas, only: [:index]
end

The above code is not nested, unlike the previous code. Now, let's run rails routes on the terminal as before and check the same part.

Prefix ➡︎ fugas Verb ➡︎ GET URI Pattern ➡︎ /fugas(.:format) Controller#Action ➡︎ fugas#index

You can see that the Prefix and URI Pattern are different compared to the previous one. Since Prefix is a simple description of URI Pattern, we will focus only on URI Pattern.

Difference between with and without routing nesting

When nested URI Pattern ➡︎ /hoges/:hoge_id/fugas(.:format) If not nested URI Pattern ➡︎ /fugas(.:format)

In other words, you can say that routing nesting is done to change the URI Pattern. However, this phrase is difficult to understand, so I will explain it in a little more detail.

You will need to specify the hoge_id for the index action of the fugas controller to work because the URI Pattern has changed due to nesting. Therefore, you can put hoge_id in params. In other words, I mentioned earlier that routing nesting is for changing the URI Pattern, but it can be rephrased as ** for putting the id information of the nesting side (hoge this time) in params **. I can do it.

By putting the id information of the nested side (hoge this time) in params, it is possible to handle the information of the nested side in the controller of the nested side (fuga this time).

Recommended Posts

What's happening with routing nesting
Nesting routing ...