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:
- take the first two characters of the
key
and make a directory- within that directory, take the next two characters of the
key
and make another directory- store the file there, and the file name is the entire
key
- store the file there, and the file name is the entire
- within that directory, take the next two characters of the
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?
CodePudding user response:
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.