2016-09-12 140 views
1

我想,将以下网址:的Rails:路线嵌套资源父资源视图

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

SectionsController#show

params[:id]8,对所有URL和params[:entry_id']202012存在时。

我该如何用路线来实现这个?

我已经有了:

resources :sections, only: [:show] 
+0

如果你想让所有以'/ sections /'开头的网址去分段控制器显示操作,请尝试:match'/ sections /',以:'sections#show',via:'get' – luissimo

回答

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助手。让我们以这个代码为例,因为它大部分类似于你所要求的。

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,并尝试了解分段密钥并命名路径帮手。

+0

谢谢。使用这个:'资源:部分,只:[:显示]做 资源:条目,只:[:index,:show],控制器:'节' end' – maxhud

1

在路线

resources :sections do 
    resources :entries 
end 

在EntriesController#show方法

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