Posted over 7 years ago. Visible to the public.

Always store your Paperclip attachments in a separate folder per environment

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, 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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Henning Koch
Last edit:
over 4 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more