Rails — Serializing Active Storage uploads with Active Model
How to serialize files uploaded with Active Storage to JSON, then upload the files via an AJAX request.
This is a short guide for Rails applications that utilize Active Storage to handle file uploads. I won’t detail that process — there’s already a recent and well-written blog on the topic that also outlines how to store the images with GCS or AWS and deploy to Heroku.
The first piece is relatively straightforward. I used Active Model to serialize data. rails g wine serializer
generates a directory for serializers, and creates a serializer for the wine class.
class WineSerializer < ActiveModel::Serializerend
From there, I added in the attributes and relationships I wanted to serialize.
class WineSerializer < ActiveModel::Serializer attributes :id, :producer, :wine_name, :wine_type, :price_range, :vintage,
:rating, :notes, :favorite
belongs_to :user
belongs_to :varietal
belongs_to :countryend
The last step is adding the Rails URL helpers, and creating a method to make the image an attribute.
class WineSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers