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
Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. A single call to resources can declare all of the necessary routes for your index , show , new , edit , create , update , and destroy actions.
Declaring a resource or resources generally corresponds to generating many default routes. resource is singular. resources is plural.
This is the simple option. When you use namespace , it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With