Supercharge your Rails App with Active Admin

railsMarch 26, 2024Dotby Alkesh Ghorpade

Introduction

Crafting robust and intuitive administrative interfaces can be a time-consuming task. Enter ActiveAdmin, a gem that revolutionizes how developers build robust and customizable admin panels. With its sleek interface and extensive feature set, ActiveAdmin simplifies creating, customizing, and managing administrative dashboards for Ruby on Rails applications. Let's delve deeper into the world of ActiveAdmin and explore its capabilities, benefits, and how to harness its full potential.

What is ActiveAdmin?

ActiveAdmin is an open-source Ruby on Rails framework that provides a simple and effective way to build elegant admin interfaces for web applications. It offers a DSL (Domain Specific Language) for defining resources, allowing developers to quickly generate their models' CRUD (Create, Read, Update, Delete) interfaces. ActiveAdmin is built on popular libraries such as Devise for authentication and CanCanCan for authorization, making it highly customizable and secure.

Getting Started with Active Admin

Installation

Add the ActiveAdmin gem to your Gemfile and run bundle install to install the gem.

# Gemfile

gem 'activeadmin'

ActiveAdmin integrates well with the below gems. You can add them to your Gemfile and execute bundle install.

# Gemfile

gem 'devise'
gem 'cancancan'
gem 'draper'
gem 'pundit'

Generate Admin Interface

Use the rails generate active_admin:install command to generate the necessary files and configuration for ActiveAdmin.

rails generate active_admin:install

The generator will create the following files.

app/admin/dashboard.rb
app/assets/javascripts/active_admin.js
app/assets/stylesheets/active_admin.scss
config/initializers/active_admin.rb

To verify the changes, execute database migration, seed the table and run your server.

rails db:migrate
rails db:seed
rails server

The seed data creates an admin user with email as [email protected] and password as password. Navigate to localhost:3000 and log in using these admin credentials. You will see the new Active Admin dashboard.

You must execute the command below, to register an existing model with Active Admin.

rails generate active_admin:resource MyModel

The command generates a file at app/admin/my_model.rb. Just refresh your browser to see the model name reflected in the UI.

If you want to use webpacker in your new Rails application, along with ActiveAdmin, you must pass the --use_webpacker option to the generator command.

rails g active_admin:install --use_webpacker

For existing applications, you must edit the ActiveAdmin initializer file.

# config/initializers/active_admin.rb

ActiveAdmin.setup do |config|
  config.use_webpacker = true
end

After setting the use_webpacker config, run the below generator command.

rails g active_admin:webpacker

Configuration

Configuring ActiveAdmin is essential for tailoring the administrative interface to fit the specific needs of your application. The gem offers a wide range of customization options, from basic settings like site title and menu items to advanced features such as customizing filters and adding custom actions. Let's explore the general configuration options in ActiveAdmin.

Authentication

Configure authentication settings to control access to the admin panel. By default, ActiveAdmin uses Devise for authentication.

# config/initializers/active_admin.rb

config.authentication_method = :authenticate_admin_user!
config.current_user_method = :current_admin_user

To turn off authentication via ActiveAdmin, set the above config features to false.

# config/initializers/active_admin.rb

config.authentication_method = false
config.current_user_method = false

Authorization

Define authorization rules to manage user permissions and access levels. ActiveAdmin integrates with CanCanCan for role-based authorization. To know more about CanCanCan, please refer to our cancancan blog post.

config.authorization_adapter = ActiveAdmin::CanCanAdapter

If you are using Pundit, set the authorization_adapter to Pundit as below.

config.authorization_adapter = ActiveAdmin::PunditAdapter

Set the title and logo for your ActiveAdmin dashboard using the site_title and site_title_image methods in the config/initializers/active_admin.rb file.

config.site_title = "My Admin Dashboard"
config.site_title_image = "/path/to/logo.png"

Dashboard Configuration

Customize the dashboard by adding widgets, panels, or custom content. You can define the dashboard layout in the app/admin/dashboard.rb file.

ActiveAdmin.register_page "Dashboard" do
  content title: "Dashboard" do
    # Add widgets or custom content here
  end
end

Customizing Resource Views

Customize the appearance and behaviour of resource views by defining custom actions, filters, and index displays.

ActiveAdmin.register User do
  actions :index, :show, :edit, :update
  filter :email
  index do
    selectable_column
    id_column
    column :email
    actions
  end
end

Configure the menu items displayed in the sidebar navigation. You can define custom menu items and organize them into categories.

config.namespace :admin do |admin|
  admin.build_menu do |menu|
    menu.add label: "Dashboard", priority: 1
    menu.add label: "Users", priority: 2
    # Add more menu items as needed
  end
end

Comments

Active Admin automatically incorporates comments on resources, which may only sometimes be desired. To deactivate comments for the resources, update the comments config to false.

ActiveAdmin.setup do |config|
  config.comments = false
end

# For a given resource:
ActiveAdmin.register User do
  config.comments = false
end

Managing resources

Managing resources is a fundamental aspect of building administrative interfaces with ActiveAdmin. Resources represent models in your Rails application, and ActiveAdmin provides various tools to work with them efficiently. Here's a guide on how to work with resources in ActiveAdmin:

Registering Resources:

To work with a model in ActiveAdmin, you need to register it. This is typically done in files within the app/admin directory. For example:

ActiveAdmin.register User do
  # Configuration for the User resource
end

This registers the User model with ActiveAdmin, allowing you to manage it through the admin interface.

Customizing Resource Views

ActiveAdmin provides DSL methods to customize the appearance and behaviour of resource views. For example, you can define index displays, show pages, forms, and custom actions.

ActiveAdmin.register User do
  index do
    selectable_column
    id_column
    column :first_name
    column :created_at
    actions
  end

  show do
    attributes_table do
      row :first_name
      row :last_name
      row :created_at
    end
  end

  form do |f|
    f.inputs "User Details" do
      f.input :first_name
      f.input :last_name
      f.input :email
    end
    f.actions
  end
end

Filters and Scopes

ActiveAdmin allows you to define filters and scopes to facilitate searching and filtering of resources. Filters are typically added to index pages, while scopes provide predefined filters.

ActiveAdmin.register User do
  filter :email
  scope :active
  scope :deactivated
end

Actions

ActiveAdmin provides built-in actions such as edit, delete, view, and new. Additionally, you can define custom actions to perform specific tasks on resources.

ActiveAdmin.register User do
  actions :index, :show, :new, :edit

  member_action :deactivate, method: :put do
    # Logic to deactive a user
  end
end

Disabling Actions

All CRUD actions are enabled by default. You can turn off actions for a given resource.

ActiveAdmin.register User do
  actions :all, except: [:update, :destroy]
end

Customizing the Index Page and CSV format

Customizing the index page in ActiveAdmin allows you to tailor the presentation of your resource's data to fit your specific needs and preferences. Users typically view a list of records for a particular model on the index page.

Sorting and Pagination

ActiveAdmin automatically handles pagination for index pages. You can configure the number of records per page and customize the pagination theme in the initializer file (config/initializers/active_admin.rb).

config.default_per_page = 20
config.pagination_theme = :ajax

Additionally, you can enable sorting by columns by specifying the sortable option:

index do
  sortable_columns :first_name, :last_name, :created_at
  # Other column definitions
end

Customizing download links in ActiveAdmin allows you to provide users with convenient ways to export data from your application. ActiveAdmin offers built-in support for exporting data to various formats such as CSV, XML, and JSON.

# Per resource

ActiveAdmin.register User do
  index download_links: false
  index download_links: [:pdf]
  index download_links: proc { current_user.can_view_download_links? }

end

# For the entire application

ActiveAdmin.setup do |config|
  config.download_links = false
  config.download_links = [:csv, :xml, :json, :pdf]
  config.download_links = proc { current_user.can_view_download_links? }
end

Please be aware that you need to implement PDF rendering for your action; ActiveAdmin doesn't offer this functionality. This configuration enables you to define formats that should be displayed within the index collection.

CSV format

When it comes to customizing the CSV format in ActiveAdmin, you have the flexibility to tailor the exported CSV file according to your specific requirements. Here's a guide on how to customize the CSV format in ActiveAdmin.

Customizing the CSV format is as simple as customizing the index page.

ActiveAdmin.register User do
  csv do
    column :email
    column(:full_name) { |user| user.full_name }
  end
end

You can customize he labels of the CSV columns by passing a label parameter to the column method:

ActiveAdmin.register Post do
  csv do
    column :id, label: "Post ID"
    column :title, label: "Post Title"
    column :author, label: "Author Name"
    column(:created_at, label: "Creation Date") { |post| post.created_at.strftime("%Y-%m-%d") }
  end
end

You can also set system-wide custom CSV settings.

# Set the CSV builder separator
config.csv_options = { col_sep: ';' }

# Force the use of quotes
config.csv_options = { force_quotes: true }

Custom Authorization Adapter

Creating a custom authorization adapter in ActiveAdmin allows you to implement complex authorization logic tailored to your application's needs.

Start by creating a new class that inherits from ActiveAdmin::AuthorizationAdapter. This class will contain your custom authorization logic.

# app/admin/custom_authorization_adapter.rb

class CustomAuthorizationAdapter < ActiveAdmin::AuthorizationAdapter
  def authorized?(action, subject = nil)
    # Your authorization logic goes here
  end
end

To use CustomAuthorizationAdapter to Active Admin, go to your application's config/initializers/active_admin.rb and add/modify the line.

config.authorization_adapter = "CustomAuthorizationAdapter"

When a controller action is performed, the CustomAuthorizationAdapter's #authorized? method will be called.

With your custom authorization adapter configured, you can now use it within your resource definitions to enforce authorization rules. For example:

ActiveAdmin.register User do
  controller do
    def scoped_collection
      if authorized?(:read, User)
        super
      else
        # Return a scoped collection based on authorization logic
      end
    end
  end
end

ActiveAdmin::AuthorizationAdapter also provides a hook method (#scope_collection) for the adapter to scope the resource;s collection. For example, you may want to centralize the scoping:

class CustomAuthorizationAdapter < ActiveAdmin::AuthorizationAdapter
  def authorized?(action, subject = nil)
    subject.account == user.account
  end

  def scope_collection(collection, action = Auth::READ)
    collection.where(account_id: user.account_id)
  end
end

Custom Pages

Custom pages in ActiveAdmin allow you to create additional pages within your admin interface to display custom content, perform specific tasks, or integrate external functionality.

Start by creating a new ActiveAdmin page using the register_page method. You can define the content of the page using the content block.

ActiveAdmin.register_page "Custom Page" do
  content title: "Custom Page" do
    # Add custom content here
  end
end

This will create a new "Custom Page" page with the specified content in the ActiveAdmin sidebar.

You can add any custom HTML, CSS, or JavaScript code within the content block to create the desired functionality or display. You can use the components and helpers Active Admin provides to generate content dynamically.

ActiveAdmin.register_page "Custom Page" do
  content title: "Custom Page" do
    panel "Custom Panel" do
      para "This is a custom panel."
    end
    # Add more custom content here
  end
end

If your custom page requires specific routes or parameters, you can define them using the controller block and specify custom routes within the associated controller.

ActiveAdmin.register_page "Custom Page" do
  controller do
    def index
      # Custom controller logic
    end
  end
end

By creating custom pages in ActiveAdmin, you can extend the functionality of your admin interface to meet specific requirements, integrate external tools or services, and provide a seamless user experience for administrators.

Decorators

Decorators in ActiveAdmin provide a convenient way to customize the appearance and behaviour of resources without directly modifying the underlying model or ActiveAdmin resource configuration. Decorators act as a separate layer between the model and the view, allowing you to encapsulate presentation logic and keep your codebase clean and organized.

# app/models/user.rb
class User < ActiveRecord::Base
end

# app/decorators/user_decorator.rb
class UserDecorator < Draper::Decorator
  delegate_all

  def profile_image
    h.image_tag model.image_url
  end
end

# app/admin/user.rb
ActiveAdmin.register User do
  decorate_with UserDecorator

  index do
    column :full_name
    column :profile_image
    actions
  end
end

Once you've defined the decorator, you can use it within your ActiveAdmin resource configuration to customize the appearance of resources. You can decorate individual resource instances or entire collections.

ActiveAdmin.register User do
  decorate_with UserDecorator

  index do
    column :id
    column "full_name", :full_name
    actions
  end
end

Using decorators in ActiveAdmin, you can separate presentation logic from your models and ActiveAdmin resource configurations, leading to a cleaner and more maintainable codebase.

Key Features of Active Admin

  • Rapid Prototyping: Quickly set up basic CRUD (Create, Read, Update, Delete) operations for your models.

  • Intuitive DSL: Leverage a clean and concise syntax to define resources, actions, and views.

  • Flexible Customization: Customize nearly every aspect of the admin interface, from layouts to individual fields.

  • Pre-built Components: Benefit from built-in components like filters, sorting, and pagination for a polished user experience.

  • Themable Interface: Tailor the look and feel of the admin panel to match your application's style.

Benefits of Using Active Admin

  • Increased Development Speed Focus on core application logic instead of spending time on repetitive admin panel development.

  • Improved Maintainability Consistent code structure and clear separation of concerns make the admin interface easier to maintain.

  • Enhanced User Experience Provide a user-friendly interface for managing data within your application.

  • Reduced Code Duplication Active Admin's abstractions minimize redundant code, keeping your codebase clean.

Conclusion

Active Admin is a powerful tool for Ruby on Rails developers who want to create efficient, user-friendly administrative interfaces. Its ease of use, flexibility, and extensive features make it a valuable addition to your Rails development toolkit. If you're looking to streamline your admin panel development process, Active Admin is worth exploring.

Closing Remark

Could your team use some help with topics like this and others covered by ShakaCode's blog and open source? We specialize in optimizing Rails applications, especially those with advanced JavaScript frontends, like React. We can also help you optimize your CI processes with lower costs and faster, more reliable tests. Scraping web data and lowering infrastructure costs are two other areas of specialization. Feel free to reach out to ShakaCode's CEO, Justin Gordon, at [email protected] or schedule an appointment to discuss how ShakaCode can help your project!
Are you looking for a software development partner who can
develop modern, high-performance web apps and sites?
See what we've doneArrow right