How do I create an admin section for my app?

I’ve built the front-end of my app and it’s working well. Now I need to add in an admin section so that things can be configured. And I’d like it to look different to the front-end so the user knows they’re in the admin section.

You want to separate your admin stuff from your other controllers and the easiest way to do that is with namespaces.

In your routes file:

You now need a Users controller – but not any Users controller; it’s an Admin::Users controller. This lives in app/controllers/admin and its views live in app/views/admin.

We have a before-filter that checks our current-user (probably using your session to check which user is logged in) and redirects if we don’t have one.

And we declare a layout of admin – so we need to add a layout.html.erb in app/views/layouts, which can link to its own CSS.

This is great, as far as it goes. But if you’ve got a whole series of admin-related controllers, you probably want to share all this stuff in an AdminController (in app/controllers/admin_controller.rb).

And our other admin-related controllers become simply:

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe