ParsaLabs | Blog

A publication about the web and more.

Namespaced Routes and Restful Controllers in Rails

| Comments

Often times in web projects it’s required that we provide distinct interface(s) to different types of users. In my opinion, a good practice in this case is to keep the business models unique, but separate controllers and views for different roles. Fortunately rails supports this out of the box with a feature called namespaced routes. If you take a look at the last commented block in your routes.rb file, you will find it hidden there. In this post, I will try to explain how to use it. So, let’s say you have a blogging application with 2 sets of users (normal, and admin) accessing the same resource (post model) but in different ways.

Controller

To generate public controller for public users:

1
rails g controller posts

For admins:

1
rails g controller admin/posts

The second generator will create controllers/admin/posts_controller.rb, and a folder for the views in views/admin/posts.

Routes

For public users:

1
resources :posts, only: [:index, :show]

And a namespaced route for the admins:

1
2
3
namespace :admin do
  resources :posts
end

As a result, you will get 2 sets of distinct routes for public and admin access. Check them out by running rake routes in terminal.

Get the form_for right (for admin)

1
2
3
<%= form_for([:admin, @post]) do |f| %>
  # your usual form helper go here..
<% end %>

Comments