Administrate Documentation

repository·main·Indexed 27 days ago

https://github.com/thoughtbot/administrate

A Rails framework for generating customizable admin dashboards. It provides clean interfaces to create, edit, search, and delete application records while staying close to standard Rails patterns. Features include support for custom dashboards, custom field types, integration with authentication systems like Clearance and Devise, and authorization via Pundit.

Tokens
12.9K
Snippets
48
Records
74
Agent score
88%

What's inside Administrate

  1. Overview of Administrate

    main

    Administrate is a framework for creating flexible, powerful admin dashboards in Ruby on Rails. It provides clean interfaces for users to create, edit, search, and delete records for any model in your application.

    Key design principles include:

    • Staying close to standard Rails patterns.
    • Supporting simple use cases while allowing overrides via standard Rails controllers and views.
    • Using a modular architecture composed of core components and plugins.
  2. Create a scoped has_many relationship in a model

    main

    To display a subset of a has_many relationship in the Administrate dashboard, define a new association in your ActiveRecord model using a scope (a proc or lambda) as the second argument. Because ActiveRecord infers the class name from the association name, you must explicitly provide the class_name option to point to the correct model.

    class Customer < ApplicationRecord
       has_many :orders
       has_many :processed_orders, ->{ where(processed: true) }, class_name: "Order"
    end
  3. Configure Admin routes and root path

    main

    After installation, you must define routes within an admin namespace in config/routes.rb. You should also define a root route within that namespace to specify which dashboard index is shown when visiting /admin.

    Rails.application.routes.draw do
      namespace :admin do
        # Add dashboard for your models here
        resources :customers
        resources :orders
    
        root to: "customers#index" # <--- Root route
      end
     end
  4. Generate a custom field with a specific 'look'

    main

    If you want to organize your field views into a specific "look" directory structure (e.g., for different visual themes), use the --look flag with the generator:

    rails generate administrate:field <field_name> --look <look_name>

    This generates views under app/views/fields/<field_name>/looks/<look_name>/ instead of the default flat structure.

    rails generate administrate:field gravatar --look custom
  5. Install Administrate with a custom namespace

    main

    By default, Administrate uses the Admin namespace. You can change this (e.g., to Supervisor) during the initial installation by providing the --namespace flag. This will change the generated controller namespaces and the routing structure.

    rails generate administrate:install --namespace=supervisor
  6. Install Administrate

    main

    Administrate is a Ruby gem for Rails applications (version 6.0 or greater) and supports Ruby 3.0 and up.

    To install, add the gem to your Gemfile, run bundle install, and then execute the installer command. The installer creates an Admin::ApplicationController and generates a Dashboard and a Controller for each of your existing ActiveRecord resources.

    # Gemfile
    gem "administrate"
    $ rails generate administrate:install
  7. Implement authentication in Admin::ApplicationController

    main

    Administrate does not include a default authentication system. You must implement your own authentication logic within your Admin::ApplicationController. The recommended pattern is to use a before_action to intercept requests and verify the user's identity.

    class Admin::ApplicationController < Administrate::ApplicationController
      before_action :authenticate_admin
    
      def authenticate_admin
        # Implement your authentication logic here
      end
    end
  8. Register a custom field in a Dashboard

    main

    To use your new custom field, add it to the ATTRIBUTE_TYPES hash within your dashboard class. Map the desired attribute to your custom field class.

    class UserDashboard < Administrate::BaseDashboard
      ATTRIBUTE_TYPES = {
        created_at: Field::DateTime,
        updated_at: Field::DateTime,
        name: Field::String,
        email: GravatarField,    # Use your custom field class here
        # ...
      }
    end
  9. Understand stable sorting in Administrate

    main

    Administrate uses Administrate::Order to control the display order of index pages and HasMany fields.

    By default, the order is set to nil, which applies the model's default sort order. When a user toggles sorting by clicking a table header attribute, Administrate applies a tiebreaker using the table's primary key to ensure stable sorting (preventing records with the same attribute value from jumping positions randomly).

    Note: If the table has no primary key (e.g., a join table), the tiebreaker is not used.

  10. Add a custom controller without a related Model

    main

    To add a custom controller that is not tied to a specific ActiveRecord model (e.g., for a statistics page), follow these four steps:

    1. Define an index route: In your config/routes.rb, define a resource with only the :index action. This is required for the controller to appear in the Administrate sidebar.
    2. Create the controller: Define a controller inheriting from Admin::ApplicationController and implement the index method to prepare any necessary instance variables.
    3. Create a Custom Dashboard: Define a class inheriting from Administrate::CustomDashboard and use the resource method to name the entry (e.g., resource "Stats"). This makes the controller visible in the Administrate UI.
    4. Create the view: Create the corresponding index view file (e.g., app/views/admin/stats/index.html.erb) to render the custom content.
    # 1. config/routes.rb
    namespace :admin do
      resources :stats, only: [:index]
    end
    
    # 2. app/controllers/admin/stats_controller.rb
    module Admin
      class StatsController < Admin::ApplicationController
        def index
          @stats = { customer_count: Customer.count, order_count: Order.count }
        end
      end
    end
    
    # 3. app/dashboards/stat_dashboard.rb
    require "administrate/custom_dashboard"
    
    class StatDashboard < Administrate::CustomDashboard
      resource "Stats"
    end
    
    # 4. app/views/admin/stats/index.html.erb
    <div style="padding: 20px">
      <h1>Stats</h1>
      <p>Total Customers: <%= @stats[:customer_count] %></p>
    </div>
  11. Enable full middleware support by disabling API-only mode

    main

    An alternative to adding middleware manually is to set config.api_only = false in config/application.rb. This ensures that flashes, sessions, and cookies are available globally when the application boots.

    # config/application.rb
    config.api_only = false