I'm trying to set up 2 levels nested route in rails where dog is a child of owner and meals is a child of dog. Can I do the following?
namespace :admin do
resources :owners do
resources :dogs
end
resources :dogs do
resources :meals
end
end
You would do
namespace :admin do
resources :owners do
resources :dogs do
resources :meals
end
end
end
But to make things less confusing, Rails has a shallow option you can add to nested routes. The reason you might do this is you would want the route to have only the information needed to find the record(s). For instance, to get owner 1's list of dogs, your route would be owners/1/dogs
, but when you want to show information for dog 5, you only need the dog's id to identify that unique record even if the dog belongs to Owner 1. Without the shallow option, the route for Dog 5 is owners/1/dogs/5
, but with it, the route is dogs/5
.
This gets especially useful when you are doing more than one level of nesting. In your situation, if dog 5 had meal 6, then the route for meal 6 would be owners/1/dogs/5/meals/6
, but with the shallow option, the route for Meal 6 is meals/6
, while the route for Dog 5's meals is dogs/5/meals
. You will appreciate using the shallow option when it comes to building the paths.
So with the shallow option, you would do
namespace :admin do
resources :owners do
resources :dogs, shallow: true do
resources :meals, shallow: true
end
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.