没有资源名称的Rails路由

我的rails应用程序有一个Section模型和一个Page模型。 一节有很多页面。

# section.rb class Section < ActiveRecord::Base has_many :pages end # page.rb class Page < ActiveRecord::Base belongs_to :section end 

假设我有一个带有’about’的段,并且该段有三页带有slu””’,’people’,’history’,一个典型路由的url可能看起来像这样:

 http://example.com/sections/about/pages/intro http://example.com/sections/about/pages/people http://example.com/sections/about/pages/history 

设置路线的最佳方法是什么,以便我可以使用这些url:

 http://example.com/about/intro http://example.com/about/people http://example.com/about/history 

为了从sectionspages所有路径中删除“部分”和“页面”,您可以使用:

 resources :sections, path: '' do resources :pages, path: '' end 

重要提示:请务必将其放在路线页面的底部。 例如,你有一个example控制器,并说你的routes.rb如下所示:

 resources :sections, path: '' do resources :pages, path: '' end resources :examples root 'home#index' 

通过上面的设置,转到http://example.com/examples会将您发送到“示例” section ,而不是examples#index ,并转到http://example.com/会将您发送到sections#index而不是home#index 。 所以,上面的配置应如下所示:

 resources :examples root 'home#index' resources :sections, path: '' do resources :pages, path: '' end