Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails routing without resource name

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
like image 504
Tyler Avatar asked May 04 '14 17:05

Tyler


People also ask

What are Rails resource routes?

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.

What is the difference between resource and resources?

Declaring a resource or resources generally corresponds to generating many default routes. resource is singular. resources is plural.

What is namespace in Rails routes?

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.


1 Answers

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
like image 185
Joe Kennedy Avatar answered Oct 08 '22 16:10

Joe Kennedy