【问题标题】:How to re-name routes?如何重命名路线?
【发布时间】:2013-11-26 17:10:16
【问题描述】:

我在我的网站上为部分和页面嵌套了路由。

  resources :sections do
    resources :pages
  end

这是一个示例网址:

sitename.com/sections/5/pages/22

我不喜欢“sections”这个名字,更喜欢“chapters”。

sitename.com/chapters/5/pages/22

我认为重命名模型会很复杂,那么我怎样才能轻松地重命名路线呢?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 routes url-routing


    【解决方案1】:

    将所需的 URL 段名称作为值传递给 path 参数:

    resources :sections, :path => :chapters do
      resources :pages
    end
    

    这会导致以下路线:

               section_pages GET    /chapters/:section_id/pages(.:format)          pages#index
                              POST   /chapters/:section_id/pages(.:format)          pages#create
             new_section_page GET    /chapters/:section_id/pages/new(.:format)      pages#new
            edit_section_page GET    /chapters/:section_id/pages/:id/edit(.:format) pages#edit
                 section_page GET    /chapters/:section_id/pages/:id(.:format)      pages#show
                              PUT    /chapters/:section_id/pages/:id(.:format)      pages#update
                              DELETE /chapters/:section_id/pages/:id(.:format)      pages#destroy
                     sections GET    /chapters(.:format)                            sections#index
                              POST   /chapters(.:format)                            sections#create
                  new_section GET    /chapters/new(.:format)                        sections#new
                 edit_section GET    /chapters/:id/edit(.:format)                   sections#edit
                      section GET    /chapters/:id(.:format)                        sections#show
                              PUT    /chapters/:id(.:format)                        sections#update
                              DELETE /chapters/:id(.:format)                        sections#destroy
    

    【讨论】:

    • 这与嵌套路由块有什么关系?
    • 嵌套关系保持不变。像往常一样声明它。
    • 好的,谢谢。如果我想将旧路径重定向到新路径,我可以使用get '/sections', to: redirect('/chapters') 还是需要更多的东西来处理嵌套路由?
    • 实际上,如果您查看正在输出的路由,您会注意到命名的路由实际上保持不变。因此,您已经拥有的对名为 sections 的路径的任何引用都将自动路由到您更新的路由。您无需声明任何其他路线即可重新路由现有路径/链接。
    • 但是我的网站或其他地方的硬编码 URL 呢?我希望他们重定向到新的模块路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 2018-05-21
    相关资源
    最近更新 更多