【问题标题】:Rails: Route nested resource to parent resource viewRails:将嵌套资源路由到父资源视图
【发布时间】:2016-09-12 17:47:52
【问题描述】:

我想路由以下网址:

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

SectionsController#show

对于所有 url,params[:id]8params[:entry_id'] 在存在时为 202012

我怎样才能用路由来完成这个?

我已经得到了:

resources :sections, only: [:show]

【问题讨论】:

  • 如果你想让所有以 '/sections/' 开头的 url 去 sectioncontrollers show action try: match '/sections/', to: 'sections#show', via: 'get'

标签: ruby-on-rails


【解决方案1】:

首先要确定您希望这些路线做什么。它们的结构使得轨道希望按如下方式对它们进行布线

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 的 section 记录和 id 为 202012 的 entry 记录),那么你可以将它们传递给 helper。

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, only: [:show] do resources :entries, only: [:index, :show], controller: 'sections' end
【解决方案2】:

在路线中

resources :sections do
  resources :entries 
end

在 EntriesController#show 方法中

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

【讨论】:

    猜你喜欢
    • 2013-01-31
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2011-05-23
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    相关资源
    最近更新 更多