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:

Copy
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:

Copy
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:

Copy
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

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Henning Koch
Last edit:
over 4 years ago
Keywords:
flickering
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