How to Upload Multiple Files With Manual File Uploader Only With Activestorage in Rails
19 NOV 2018
3 mins read
With introduction of ActiveStorage in Rails 5.2 it has become easier to attach files to ActiveRecord models in Rails. So much so that Paperclip has decided to cease support for their gem and encouraging users to migrate to ActiveStorage for more streamlined solution.
While ActiveStorgae provides straightforward ways to attach files to models using has_one_attached and has_many_attached, the official guides, stackoverflow and online tutorials don’t have an example of a simple uploader to only upload files to a service or local storage in case of development. An example could be a WYSIWYG editor file uploader.
A simple file uploader can be written using ActiveStorage::Blob and url_for. Here we will see an example to upload multiple images using a simple uploader with ActiveStorage.
First we might define route to our controller like:
In our controller:
We try to avoid putting too much logic in controller. So, we put the ImageUploader in a namespaced directory inside the controllers dir.
We place the file upload logic sperate in lib dir. So, that now it is easier if we want to create another uploader for .pdf file type or testing.
Create a simple form with file upload fields taking multiple files at once:
And just like that we have a file uploader we can use to upload files straight to our preferred service. Write to me at [email protected] with questions or leave a comment. Cheers!