← Back to Upcase

Change the scope of routes to 'admin' for specific actions

(Shankar Dhanasekaran) #1

I have a category model and in my routes.rb, I have

resources :categories
which generates the following set of routes.

categories_path      GET     /categories(.:format)           categories#index
                     POST    /categories(.:format)           categories#create
new_category_path    GET     /categories/new(.:format)       categories#new
edit_category_path   GET     /categories/:id/edit(.:format)  categories#edit
category_path        GET     /categories/:id(.:format)       categories#show
                     PATCH   /categories/:id(.:format)       categories#update
                     PUT     /categories/:id(.:format)       categories#update
                     DELETE  /categories/:id(.:format)       categories#destroy

Now, what I need is except for all GET routes, I want the rest of the routes to be under ‘/admin’ scope. So that operations like create, edit and delete are accessed at admin/categories/:id/edit etc.

Is there an easy way to mention this scope?

(Joel Quenneville) #2

@shankard, you could do the following

resources :categories, only: [:index, :show, :new, :edit]

namespace :admin do
  resources :categories, only: [:create, :update, :destroy]

Check out this rails guide on routing for more info.

(Crispin Cornett) #3

Also check out scopes in the Rails Guides Routing section:

resources :categories, only: [:index, :show, :new, :edit]
scope '/admin' do
  resources :categories, only: [:create, :update, :destroy]

Using scope lets you use the same CategoriesController. If you use namespace you’d need to set up a new controller (e.g.):

# app/controllers/admin/categories_controller.rb

module Admin
  class CategoriesController < ApplicationController
    # admin actions

(Crispin Cornett) #4

Although maybe you want the new and edit actions in the admin scope as well?

resources :categories, only: [:index, :show]

scope '/admin' do
  resources :categories, except: [:index, :show]