Paperclip to Active Storage (That you can understand)

Cody Elhard
2 min readApr 9, 2021

Considering that there was a large amount of companies that had to migrate from paperclip to Active Storage I was mind blown that there was no easily understandable solutions.

I mean seriously, I found a messy SQL query in every blog.

query = <<~SQL NOT EXISTS( SELECT * FROM active_storage_blobs AS blobs INNER JOIN active_storage_attachments AS attachments ON attachments.blob_id = blobs.id WHERE record_type = ? AND record_id = #{model.table_name}.id ) SQL

Paperclip has methods to download files, why not use them. All we have to do is add an active storage attachment to our model and attach the files from there.

Step 1 — copy to active storage column

model ActiveRecordModel  has_attached_file :image  has_one_attached :photoend

Step 2 — Add method to copy from paperclip to Active Storage

Call the method as many times as you would like in a rake task for each paperclip attachment. In our case use the following params.

  • model = ActiveRecordModel
  • paperclip_method = ‘image’
  • active_storage_method = ‘photo’
def copy_paperclip_attachment_to_active_storage(model, paperclip_method, active_storage_method)  model.find_each do |resource|    next unless resource.send(paperclip_method).file?    begin      Tempfile.create do |tmp_file|        resource.send(paperclip_method).copy_to_local_file(nil, tmp_file.path)        resource.send(active_storage_method).attach(          io: tmp_file,          filename: resource.send(“#{paperclip_method}_file_name”),          content_type: resource.send(“#{paperclip_method}_content_type”)        )      end    rescue StandardError => e        ap ‘error’        ap e    end  endend

Step 2 - Fix your views

  • image_tags will not need any adjusting
  • You may experience some paperclip methods at are different with active storage
  • In our case we had to update how URLs are returned on resized images
  • For example, ActiveRecordModel.image.url(:medium) became url_for(ActiveRecordModel.photo.variant(resize_to_fit: [100, 100])

Step 3 — Models / Controllers / Active Admin

  • Hopefully, you have a well tested app here to point out the failures, but in our case we only had to update Active Admin on this step.

Closing Notes

  • This is half the picture. Merge this pull request and run your rake task and make sure everything works. Otherwise revert
  • Then, you can safely remove your paperclip methods from your model and finally the gem paperclip
  • Feel free to reach out for help, or to clear anything up. https://github.com/cody-elhard
  • Best of Luck! 🥂

NOTE: If you are a larger company, you will want to copy to active storage and then update your views in two separate pull request. Otherwise, the downtime could have a large impact.

--

--

Cody Elhard
0 Followers

Software Developer, Aspiring Entrepreneur, Ag Tech Innovator, Car enthusiast, Gym Rat