Always store your Paperclip attachments in a separate folder per environment

Updated . Posted . Visible to the public.

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


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

Henning Koch
Last edit
Keywords
flickering
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-07-28 16:51)