How to change a filename in Rails Active Storage
Ensure that downloaded files have the name you want
If you’ve tried it, you know that Active Storage provides a flexible and feature-rich Rails file management solution. Under the hood, the blobs and attachments can seem confusing at first, but it’s actually remarkably simple to set up and use.
I recently ran into a challenge, though, when trying to change the name of the files that I was uploading. The goal was to standardize and set the filename format so that no matter what a file might have been named when I uploaded it, it would be overwritten. Then, when a user would download the file later, it would have the standardized name.
I couldn’t find mention of exactly how to accomplish this, but it turns out updating the blob filename is all that’s required:
self.active_storage_object.blob.update(filename: "desired_filename.#{self.active_storage_object.filename.extension}")
In my case, I used an after_create
callback to wrap this because I was using one form to both create the object (a product) and upload and attach a file (a video) to it. Here’s that in a gist:
Don’t forget, it’s also critical to retain the extension as above when saving over the filename!