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.
To generate public controller for public users:
The second generator will create controllers/admin/posts_controller.rb, and a folder for the views in views/admin/posts.
For public users:
And a namespaced route for the admins:
1 2 3
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