[英]Rails: Route nested resource to parent resource view
我想路由以下網址:
/sections/8
/sections/8/entries/202012
/sections/8/entries/202012#notes
到SectionsController#show
對於所有 url, params[:id]
為8
, params[:entry_id']
存在時為202012
。
我怎樣才能通過路線做到這一點?
我已經有了:
resources :sections, only: [:show]
第一件事是確定您希望這些路由做什么。 它們的結構使得 rails 需要按如下方式路由它們
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 的部分記錄和 id 為 202012 的條目記錄),那么您可以將它們傳遞給幫助程序。
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並嘗試了解段鍵和命名路徑助手。
在路線中
resources :sections do
resources :entries
end
在 EntriesController#show 方法中
redirect_to section_path(id: params[:section_id], entry_id: params[:id])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.