我的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
设置路线的最佳方法是什么,以便我可以使用这些网址:
http://example.com/about/intro
http://example.com/about/people
http://example.com/about/history
答案 0 :(得分:6)
为了删除&#34;部分&#34;和&#34;页面&#34;在sections
和pages
的所有路线中,您都可以使用:
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
会将您转到&#34;示例&#34; section
而不是examples#index
,转而http://example.com/
会将您发送到sections#index
而不是home#index
。因此,上面的配置应如下所示:
resources :examples
root 'home#index'
resources :sections, path: '' do
resources :pages, path: ''
end