Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use ActiveAdmin on a non-ActiveRecord based model (say activeModel or Mongoid, etc)?

Question pretty much says it all.

I've got an existing site that supports a well defined API.

I need to build up a nice management interface for it, and, since I've used ActiveAdmin to create effect before, I'd love to use it here to.

However, I can't find any details on whether doing so is even possible.

I've read comments saying that AA support ActiveModel type objects, that don't have to be based on ActiveRecord, but I've had no long trying that myself, or finding any examples of such.

Anyone know if this is even possible?

like image 441
DarinH Avatar asked Nov 04 '13 16:11

DarinH


1 Answers

I was able to achieve this by using an ActiveAdmin custom page.

For our example we have a model called MailingList. This is a Ruby class that includes some ActiveModel abilities.

# app/models/mailing_list.rb
class MailingList
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name
  validates_presence_of :name

   def initialize(args)
     # Set up instance variables
   end

   def self.all
     # Use API to retrieve list of records
   end

   def save(args)
     # Use API to save record
   end

   def id
     # Unique identifier from API
   end

   def persisted?
     false
   end
end

To use this API driven model in ActiveAdmin we create a page like so.

# app/admin/mailing_list.rb
ActiveAdmin.register_page 'Mailing Lists' do

  action_item do
     link_to 'New Mailing List', admin_mailing_lists_new_path
  end

  content do
    redirect_to :index
  end

  page_action :index do
    @mailing_lists = MailingList.all
    render :index, :layout => 'active_admin'
  end

  page_action :show do
    render :show, :layout => 'active_admin'
  end

  page_action :new do
    @mailing_list = MailingList.new
    render :new, :layout => 'active_admin'
  end

  page_action :create, :method => :post do
    @mailing_list = MailingList.new(params[:mailing_list])
    if @mailing_list.save
      redirect_to admin_mailing_list_path(@mailing_list.id)
    else
      render :new, :layout => 'active_admin'
    end
  end

end

The page_action methods act as controller actions.

To get this to work as expected I had to add the following routes

# config/routes.rb
post '/admin/mailing_lists' => 'admin/mailing_lists#create'
get '/admin/mailing_lists/new' => 'admin/mailing_lists#new', :as => :admin_new_mailing_list
get '/admin/mailing_lists/:id' => 'admin/mailing_lists#show', :as => :admin_mailing_list

You will also need some views in

app/views/admin/mailing_lists/index.html.erb app/views/admin/mailing_lists/show.html.erb app/views/admin/mailing_lists/new.html.erb

like image 151
bennick Avatar answered Oct 12 '22 23:10

bennick