7

Is there a way to write the following routes so you don't have to specify the same controller each time?...

get 'jobs' => 'pages#jobs'
get 'contact' => 'pages#contact'
get 'terms' => 'pages#terms'
get 'privacy' => 'pages#privacy'

1 Answer 1

18

Here are couple of alternatives:

Out of the three, the first one i.e., Using scope as "/" would create the exact same routes as the ones created by the routes defined in the question.

1. Using scope as "/"

scope "/", controller: :pages do
  get 'jobs' 
  get 'contact' 
  get 'terms' 
  get 'privacy' 
end

Creates routes as below:

jobs    GET    /jobs(.:format)                      pages#jobs
contact GET    /contact(.:format)                   pages#contact
terms   GET    /terms(.:format)                     pages#terms
privacy GET    /privacy(.:format)                   pages#privacy

2. Using Scope as "pages"

scope :pages, controller: :pages do
  get 'jobs' 
  get 'contact' 
  get 'terms' 
  get 'privacy' 
end

Creates routes as below:

jobs    GET    /pages/jobs(.:format)                pages#jobs
contact GET    /pages/contact(.:format)             pages#contact
terms   GET    /pages/terms(.:format)               pages#terms
privacy GET    /pages/privacy(.:format)             pages#privacy

3. Nesting routes

resources :pages do
  member do
    get 'jobs' 
    get 'contact' 
    get 'terms' 
    get 'privacy' 
  end
end

Creates routes as below:

jobs_page    GET    /pages/:id/jobs(.:format)            pages#jobs
contact_page GET    /pages/:id/contact(.:format)         pages#contact
terms_page   GET    /pages/:id/terms(.:format)           pages#terms
privacy_page GET    /pages/:id/privacy(.:format)         pages#privacy
1
  • If the controller and the scope is the same, for #2, there is another way using namespace like this namespace :pages do;get 'contact';end, which will give routes like this GET /pages/contact(.:format) pages#contact
    – rubyprince
    Jun 11, 2014 at 12:05

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.