的第一件事是確定你想要的這些路由做。它們是結構化的吮指軌道會想他們的路線如下
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