简体   繁体   English

轨道中的 2 级嵌套路线

[英]2 levels nested route in rails

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.我正在尝试在铁轨中设置 2 层嵌套路线,其中狗是主人的孩子,而饭菜是狗的孩子。 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.但是为了让事情不那么混乱, Rails 有一个浅层选项,您可以将其添加到嵌套路由中。 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 .例如,要获取所有者 1 的狗列表,您的路线将是owners/1/dogs ,但是当您想显示狗 5 的信息时,即使狗属于所有者,您也只需要狗的 id 即可识别该唯一记录1. 如果没有 shallow 选项,Dog 5 的路线是owners/1/dogs/5 ,但有了它,路线是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 .在您的情况下,如果狗 5 吃了 6 餐,那么 6 餐的路线将是owners/1/dogs/5/meals/6 ,但是如果使用浅选项,则第 6 餐的路线是meals/6 ,而路线Dog 5 的餐食是dogs/5/meals You will appreciate using the shallow option when it comes to building the paths.在构建路径时,您会喜欢使用 shallow 选项。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM