Approx 4 minutes read

Active Admin is an administration framework for Ruby on Rails applications which helps in creating beautiful administration panels. Paperclip is a file attachment library for Active Record which makes management of files to models really easy.

Recently while creating administration page for a model, in which Paperclip was being used for managing attachments, I oberved that Active Admin was not handling it properly. For example, the view page was showing as below:

And the edit and new page was being shown as below:

There was no way one could upload the images with above interface. Hence I scoured internet and found some nifty hacks. Let’s go through each of them:

View Page

Instead of showing attached image properties, I wanted to show the image itself. Also for other attached files types (like pdf and doc), I wanted to give an URL. Below code achieved the same:

 1 ActiveAdmin.register Item do
 2   show do |recipe|
 3     attributes_table do
 4       row :instruction do
 5         item.instruction? ? link_to(item.instruction_file_name, item.instruction.url) : content_tag(:span, "No instruction file yet")
 6       end
 7       row :photo do
 8         item.photo? ? image_tag(item.photo.url, height: '100') : content_tag(:span, "No photo yet")
 9       end
10     end
11     active_admin_comments
12   end
13 end

This resulted in following:

New and Edit Page

I wanted to show an upload button to upload files. Also I wanted to show current file attached on Edit page so users can verify the attached content before modifying it. The code below achieved the same:

1 ActiveAdmin.register Item do
2   form :html => { :enctype => "multipart/form-data" } do |f|
3     f.inputs do
4       f.input :instruction, hint: f.item.instruction? ? link_to(f.item.instruction_file_name, f.item.instruction.url) : content_tag(:span, "Upload PDF file")
5       f.input :photo, hint: f.item.photo? ? image_tag(f.item.photo.url, height: '100') : content_tag(:span, "Upload JPG/PNG/GIF image")
6     end
7     f.actions
8   end
9 end

This resulted in following:

Note that you have to set enctype attribute in your form to multipart/form-data to enable upload of files.

And that’s it. I was pretty happy with the end result. Do let me know in comments if you happen to know any other trick.

comments powered by Disqus