Search code examples
ruby-on-railsrails-activestorage

Rails Active Storage REST API


I've been able to set up Active Storage file uploads and now I'm trying to return associated images when I do, for instance, Speaker.all or Speaker.find(2).

Calling the associated endpoint I get something like:

{
    "id": 2,
    "name": "Rafael",
    "email": "rafael.almeida@mail-provider.com",
    "company": "XING",
    "social_media": "{\"twitter\": \"@rafaelcpalmeida\"}",
    "created_at": "2018-10-01T17:21:50.993Z",
    "updated_at": "2018-10-01T17:21:51.144Z"
}

How can I also return its associated avatar?


Solution

  • I figured out what to do in order to achieve the result I wanted. First, we need to add the active_model_serializers to the Gemfile, followed by bundle install.

    After we installed the gem we should add include ActionController::Serialization to every controller that's going to use the Serializer.

    We generate a new serializer using rails g serializer speaker. My SpeakerSerializer looks like:

    class SpeakerSerializer < ActiveModel::Serializer
      attributes :id, :name, :email, :company, :avatar
    
      def avatar
        rails_blob_path(object.avatar, only_path: true) if object.avatar.attached?
      end
    end
    

    And my output looks like

    {
        "speaker": {
            "id": 2,
            "name": "Rafael",
            "email": "rafael.almeida@xing.com",
            "company": "XING",
            "avatar": "/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--515a0de8817b3529b5d3d168871cebf6ccee0463/xing-photo.jpg"
        }
    }