要满足 Rails 的要求,您只需将 shallow: true 添加到每个嵌套的 resources:
resources :stores do
resources :locations, shallow: true do
resources :business_hours, shallow: true
end
end
正如他们所说,这会产生“用最少的信息来唯一标识资源的路由”,如下所示:
Prefix Verb URI Pattern Controller#Action
location_business_hours GET /locations/:location_id/business_hours(.:format) business_hours#index
business_hour GET /business_hours/:id(.:format) business_hours#show
store_locations GET /stores/:store_id/locations(.:format) locations#index
location GET /locations/:id(.:format) locations#show
stores GET /stores(.:format) stores#index
store GET /stores/:id(.:format) stores#show
locations 的收集操作,例如。 index,嵌套在stores 下,因为locations 属于stores,但是要识别特定位置,路由引用locations/1 不带stores/ 前缀,因为您不需要store标识location 的ID。
这会沿着树向下级联:要识别 business_hours 收集操作,您需要时间所属的 location,但是因为您有一个 location ID,所以您不需要涉及 store,所以你得到locations/:id/business_hours。当您需要特定的时间时,您不再需要 location,因此您只需获得 /business_hours/1。
如果您想维护小时收集路径的整个层次结构(即/stores/1/location/2/business_hours),您需要不使用shallow 您的locations 路径,这将保留其成员操作(show, edit 等)在 /stores/1/locations/2 下,或者您需要使用较少的 Rails 帮助程序手动指定您想要的路径。