DEV Community


An Easy Admin Panel - Rails 6

I am a software engineer in training.
・2 min read

Having an admin panel in your Rails application is honestly, to me, the best thing to do when it comes to keeping track of your users and giving them permissions. Finding out how to have an admin panel though, that was tough, mainly because I wasn’t searching for the right thing. The rails_admin gem, so simple but can control so much! The installation and usage is very simple depending on what you are trying to use it on. I should probably tell you, I am using devise with the user having a boolean attribute called admin.

 create_table "users", force: :cascade do |t|
    t.boolean "admin", default: false
Enter fullscreen mode Exit fullscreen mode


The installation all starts with you putting gem ‘rails_admin’ in your gemfile amd running bundle in your terminal. After you bundle, you will need to run the rails admin generator - rails g rails_admin:install - doing so will ask you a question, just go ahead and hit enter. Once the generator is done, it will create a new route (“/admin”) and an initializer too.

You basically have it all working now. Just go to http://localhost:3000/admin and you should be brought to the admin panel! You can navigate this as much as you want to get a feel for where everything is.

We now need to add some authorization to the initializer. If you go to config/initializers/rails_admin.rb and add this line of code:

   config.authorize_with do
      redirect_to main_app.root_path unless warden.user.admin == true
Enter fullscreen mode Exit fullscreen mode

Great! Now the only users that can access your admin panel are the ones that are admins. If you need to make yourself and admin go into the rails console with rails c in the terminal and put in these 3 lines:

u = User.first
u.admin = true 
Enter fullscreen mode Exit fullscreen mode

Now your user has admin so you can mess around in the admin panel.

Navigation to Admin Panel

If you check rails routes you will notice at the very top there is a new route called rails_admin, we will use this to get a navigation button that only the admin can access. Go to where your header or navigation bar is located and add this line of code wherever you want:

<%= link_to "Admin Panel", rails_admin_path, class:"btn btn-default mb-2 lg:mr-2 lg:mb-0 block" if admin? %>
Enter fullscreen mode Exit fullscreen mode

I have an admin? Helper method so if the user is an admin, they will be able to see the navigation button to the admin panel. In order to do this we will need to go into our helpers in the application_helper.html.erb and add this method:

   def admin?
        user_signed_in? && current_user.admin?
Enter fullscreen mode Exit fullscreen mode

That’s it! You should now have a perfect admin panel that is easy to setup and easy to use!

Discussion (0)