问题
My rails app has a Section model and a Page model. A section has many pages.
# section.rb
class Section < ActiveRecord::Base
has_many :pages
end
# page.rb
class Page < ActiveRecord::Base
belongs_to :section
end
Assuming I have a Section with slug 'about', and that section has three pages with slugs 'intro', 'people', 'history,' a url with typical routing might look something like this:
http://example.com/sections/about/pages/intro
http://example.com/sections/about/pages/people
http://example.com/sections/about/pages/history
What is the best way to set up my routes so that I can use these urls:
http://example.com/about/intro
http://example.com/about/people
http://example.com/about/history
回答1:
In order to remove "sections" and "pages" from all routes for both sections
and pages
, you could use:
resources :sections, path: '' do
resources :pages, path: ''
end
Important: be sure to put this to the bottom of your routes page. For instance, it you have an example
controller, and say your routes.rb
appeared as follows:
resources :sections, path: '' do
resources :pages, path: ''
end
resources :examples
root 'home#index'
With the above setup, going to http://example.com/examples
would send you to the "examples" section
, rather than than examples#index
, and going to http://example.com/
would send you to sections#index
rather than home#index
. So, the above configuration should look like this:
resources :examples
root 'home#index'
resources :sections, path: '' do
resources :pages, path: ''
end
来源:https://stackoverflow.com/questions/23459140/rails-routing-without-resource-name