It appears that by default, Rails Active Storage nests your file uploads by means of the associated active_storage_blob
key
.
The rules appear to be as follows for the default behavior. Within the <Rails.root>/storage/
directory:
key
and make a directory
key
and make another directory
key
For example: where the key
of a particular file's associated active_storage_blob
is: 2HadGpe3G4r5ygdgdfh5534346, It would look like the following:
I do not want this nesting behavior. I want to store the files flat within the storage directory. So I simply want it to look like this:
.
How can I do that? A google search and a read through of the Active Storage Rails Guides didn't reveal a solution.
Also just out of curiosity: why is this the default behavior?
The new approach to file uploads | Prograils Update: Rails and Active Storage. The new approach to file uploads Since its first shipping, Active Storage has revolutionized attaching files to Ruby on Rails applications. Learn what it is, how to set it up and use it, as well what's new in Rails Active Storage in 2021!
The files are uploaded to cloud storage services like Amazon S3, Google Cloud Storage or Microsoft Azure Storage and then attached to Active Record objects in the app. This means Rails developers no longer have to use third-party libraries like CarrierWave for example.
Before we begin, make sure you have ruby version >= 2.5.0 and Rails version 5.2.0. The ActiveStorage gem is included on Rails 5.2 by default. You can simply check your version: [ If your ruby version is not up to date, you can update it with a ruby version manager like rvm or rbenv.
Even though Rails provides JSON serialization by default, we’re going to use ActiveModel::Serializer, because in a real application the framework feature is usually not enough. ActiveModel::Serializer encapsulates the JSON serialization of object.
Digging around in the code of the ActiveStorage DiskService, I found the code which generates the folder structure. All is conveniently contained within a single function:
def folder_for(key)
[ key[0..1], key[2..3] ].join("/")
end
This makes it easy to eliminate the two-letter subfolder structure by a simple patch:
module ActiveStorage
class Service::DiskService < Service
private
def folder_for(key)
""
end
end
end
Best to do a little testing on this patch, but as far as I could tell it should work just fine.
The answer to the second question I was not able to determine by just looking at the DiskService code. There are no clues there to this folder structure, so the reasons may lie elsewhere. It may be done entirely for cosmetic purposes, in order to avoid a giant single folder blob on large servers. Perhaps someone who knows more can comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With