的第一件事是确定你想要的这些路由做。它们是结构化的吮指轨道会想他们的路线如下
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你可以改变第一路线跟随宁静的路线。
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和条目记录ID 202012),那么你可以将它们传递给帮手。
section = Section.find(8)
entry = section.entries.find(202012)
section_entry_path(section, entry) # => returns path string /sections/8/entries/202012
欲了解更多信息,请阅读铁轨路线导向http://guides.rubyonrails.org/routing.html,并尝试了解分段密钥并命名路径帮手。
如果你想让所有以'/ sections /'开头的网址去分段控制器显示操作,请尝试:match'/ sections /',以:'sections#show',via:'get' – luissimo