Rails:将嵌套资源路由到父资源视图

时间:2016-09-12 17:47:53

标签: ruby-on-rails

我想路由以下网址:

/sections/8
/sections/8/entries/202012
/sections/8/entries/202012#notes

SectionsController#show

并且params[:id]为所有网址8params[:entry_id']202012

如何通过路线实现这一目标?

我已经有了:

resources :sections, only: [:show]

2 个答案:

答案 0 :(得分:2)

首先要确定您希望这些路线做什么。他们的结构很糟糕,铁路将要按如下方式路由它们

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 helpers。我们以此代码为例,因为它大部分类似于您的要求。

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并尝试了解段密钥和命名路径帮助程序。

答案 1 :(得分:1)

路线

resources :sections do
  resources :entries 
end

在EntriesController #show方法

redirect_to section_path(id: params[:section_id], entry_id: params[:id])