Rails controller namespaces

Mainly used if you have actions on the same controller that deals with “admin” and “non-admin” users. This eliminates the need to put a lot of redundant checking on actions just to differentiate from these roles. And also, it’s a nice way to organize your codes.

config/routes.rb:
map.namespace :admin do |admin|
   admin.resources :posts
end
controllers/admin/posts_controller.rb
class Admin::PostsController < ApplicationController
    before_filter :assert_if_admin
    # some code. . .
    private
    def assert_if_admin
      unless current_user.is_admin?
        redirect_to root_path
      end
    end
end

and that’s it! just change the routes of your links to point to specific actions on the namespaced controller 🙂

also, if you have form_for @post added in your code, you can change it to use the namespaced route to: form_for [:admin, @post], this will generate a path /admin/posts/ to your form

🙂

source: http://stackoverflow.com/questions/119197/the-rails-way-namespaces

Leave A Comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked