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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)