Manual uploads using Active Storage

Rails 5.2 will come with its own flavor of file uploading solution called Active Storage. It has a really convenient way of attaching one or many files to a model using the has_one_attached and has_many_attached. But in some cases, you might need to manually upload a file. For example, an image used in a WYSIWYG editor.

Although this is not documented, it can be done in just a couple of steps, by using the ActiveStorage::Blob and url_for.

First we need to add our new route to routes.rb.

post 'uploader/image', to: 'uploader#image'

Now we need to create our controller with the required action.

Even though, it is not present in the how to use documentation, a quick look at the source code revealed that there are а couple of convenient methods that can be used. The key one here is create_after_upload! method, which is used to store the uploaded image. Later we can use url_for to generate url for the blob that can be used by the editor.

Need help with Ruby on Rails? At Evermore we’ve been using it for some time.