Read more

Always store your Paperclip attachments in a separate folder per environment

Henning Koch
July 28, 2011Software engineer at makandra GmbH

tl;dr: Always have your attachment path start with :rails_root/storage/#{Rails.env}#{ENV['RAILS_TEST_NUMBER']}/.


Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

The directory where you save your Paperclip attachments should not look like this:

storage/photos/1/...
storage/photos/2/...
storage/photos/3/...
storage/attachments/1/...
storage/attachments/2/...

The problem with this is that multiple environments (at least development and test) will share the same directory structure. This will cause you pain eventually. Files will get overwritten and your tests will see files where there should be none. Also when you are using parallel_tests Show archive.org snapshot , test processes will overwrite each other's files.

You should store your Paperclip attachments in a separate folder per environment and parallel_tests test number instead:

storage/development/photos/1/...
storage/development/photos/2/...
storage/development/photos/3/...
storage/development/attachments/1/...
storage/development/attachments/2/...
storage/test/photos/1/...
storage/test/photos/2/...
storage/test/attachments/1/...
storage/test/attachments/2/...
storage/test2/photos/1/...
storage/test2/photos/2/...
storage/test2/attachments/1/...
storage/test2/attachments/2/...

In order to implement this, make Rails.env and ENV['RAILS_TEST_NUMBER'] part of your path template:

has_attached_file :attachment, :path => ":rails_root/storage/#{Rails.env}#{ENV['RAILS_TEST_NUMBER']}/attachments/:id/:style/:basename.:extension"

Think of existing attachments when you upgrade a live application with this.

Further reading

Common mistakes when storing file uploads with Rails

Posted by Henning Koch to makandra dev (2011-07-28 18:51)