ActiveAdmin in an API-only application - step by step

1/ Generate a new app:

rails new apibe_active_admin --api

2/ Adding new gems and bundle

gem 'activeadmin'

gem 'devise' # ActiveAdmin depends on Devise for authentication

gem 'sass-rails' # Required for ActiveAdmin styling

3/ Install devise

rails generate devise:install

4/ Generate user and run migrate

rails generate devise User

rails db:migrate

5/ Install activeadmin

rails generate active_admin:install

An error happened regarding the layout method:
/var/lib/gems/3.2.0/gems/activeadmin-3.2.5/lib/active_admin/devise.rb:31:in `block in <module:Controller>': undefined method `layout' for ActiveAdmin::Devise::SessionsController:Class (NoMethodError)

        layout "active_admin_logged_out"
        ^^^^^^
        from /var/lib/gems/3.2.0/gems/activesupport-7.1.4/lib/active_support/concern.rb:138:in `class_eval'

To fix this, we need to create new controller ApiController inherits ActionController::API
And ApplicationController to inherits ActionController::Base

6/ Run db migrate to update the db, and start server
7/ We need to add below code to use some middlewares required by devise.
    # Use middleware for API-only applications
    config.middleware.use ActionDispatch::Cookies
    config.middleware.use ActionDispatch::Session::CookieStore
    config.middleware.use Rack::MethodOverride
    config.middleware.use ActionDispatch::Flash

8/ Run db seed and restart the server
9/ ActiveAdmin works now. To fix ransack issue, follow this link: https://stackoverflow.com/a/78448378

Back to posts