Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use same controller for multiple routes?

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'
like image 366
user3188544 Avatar asked Mar 31 '14 23:03

user3188544


1 Answers

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
like image 160
Kirti Thorat Avatar answered Nov 02 '22 18:11

Kirti Thorat