首先要确定您希望这些路线做什么。它们的结构使得轨道希望按如下方式对它们进行布线
resources :sections, only: [:show] do
resources :entries, only: [:show]
end
# /sections/8 => SectionsController#show
# /sections/:id
#
# /sections/8/entries/202012 => EntriesController#show
# /sections/:section_id/entries/:id
#
# /sections/8/entries/202012#note => EntriesController#show
# /sections/:section_id/entries/:id
但是,如果您希望所有这些都映射到 SectionsController,您可以更改第一个路由以遵循 restful 路由。
resources :sections, only: [:show] do
resources :entries, only: [:index, :show], controller: 'sections'
end
# /sections/8/entries => SectionsController#index
# /sections/:section_id/entries
#
# /sections/8/entries/202012 => SectionsController#show
# /sections/:section_id/entries/:id
#
# /sections/8/entries/202012#note => SectionsController#show
# /sections/:section_id/entries/:id
如果您决定将所有这些路由转到单个控制器,我不建议这样做,那么您可以明确定义您的路由。
get '/sections/:id', to: 'sections#show'
get '/sections/:id/entries/:entry_id', to: 'sections#show'
要使用这些路由,您将使用 rails url 助手。让我们以这段代码为例,因为它与您的要求很相似。
resources :sections, only: [:show] do
resources :entries, only: [:index, :show], controller: 'sections'
end
section_entries_path 是索引视图的助手。 section_entry_path 是您的展示视图的助手。如果你有你需要的记录(即 id 为 8 的 section 记录和 id 为 202012 的 entry 记录),那么你可以将它们传递给 helper。
section = Section.find(8)
entry = section.entries.find(202012)
section_entry_path(section, entry) # => returns path string /sections/8/entries/202012
有关更多信息,请阅读 rails 路由指南http://guides.rubyonrails.org/routing.html 并尝试了解段键和命名路径帮助器。