Skip to content

Custom File Processing Forms in Active Admin

Posted on:January 18, 2016

I needed to add a form to Active Admin so that a client could upload tsv files, which would be parsed and the data added to the database. Here’s how I did it.

In app/admin, register the relevant model with ActiveAdmin. In this case, the tsv files contain information of users, which would be loaded into the database, so we park it under the User model.

# app/admin/user.rb
ActiveAdmin.register User, namespace: :activeadmin do
  # other Active Admin stuff
end

Then, we add an action_item to the User panel, and associate that with a collection_action, which we use to render a form partial.

# app/admin/user.rb
ActiveAdmin.register User, namespace: :activeadmin do
  # other Active Admin stuff
  action_item only: :index do
    link_to 'Upload TSV', action: 'upload_tsv'
  end
 
  collection_action :upload_tsv do
    render 'admin/tsv/upload_tsv'
  end
end

# app/views/admin/tsv/upload_tsv/html.erb
<%= form_tag({action: :import_tsv}, multipart: true) do %>
  <%= file_field_tag 'tsv_file' %>
  <%= submit_tag "Upload TSV" %>
<% end %>

We indicate the :import_tsv action in the form partial, which is added as below:

# app/admin/user.rb
collection_action :import_tsv, method: :post do
  # tsv parsing logic here
  flash[:notice] = "TSV file imported successfully!"
  redirect_to action: :index
end

This action can contain any arbitrary parsing application logic, the result of which can be displayed to the user in a flash notice, as demonstrated simply above. Also note that the file is not stored subsequently.