9

I am using rails-api gem in my project for json api, and for that purpose I used active model serializer gem for serializing my objects but some how the objects are not being serialized using active model serializer.

I have a MessageSerializer inside of my serializers folder

class MessageSerializer < ActiveModel::Serializer
  attributes :id, :sender_id, :recipient_id, :sender_type, :subj, :body, :status, :sender

  def sender
    object.user.try('username')
  end
end

And my messages controller is as follows

class Api::MessagesController < Api::BaseController

  def index
    @messages = current_user.incoming_messages
    render json: @messages, serializer: MessageSerializer
  end

end

But the problem is that the serialized object thrown to client contains all the fields in message model ie; it contains created_at, updated_at fields too.

Seems like its not using serializer.

What might have gone wrong? I searched a lot about it but didn't found any post that helped me.

Thanks

Gagan
  • 4,278
  • 7
  • 46
  • 71
  • change this to `class Api::MessagesController < Api::BaseController` to `class Api::MessagesController < ApplicationController` and change this also render json: @messages and try once – Gowri Nov 05 '14 at 02:50
  • No not good. Api::BaseController class inherits ApplicaionController class. So basically its the same. – Gagan Nov 06 '14 at 02:04

4 Answers4

16

In your BaseController, did you add the include bellow ?

include ActionController::Serialization

Edouard Brèthes
  • 1,142
  • 11
  • 25
10

What version of AMS are you using?

I had this same issue and was able to fix it by changing the AMS version from 0.9.X to 0.8.X. This can be done by adding a version number to your Gemfile.

gem 'active_model_serializers', '~> 0.8.0'

There are notes about this on the AMS GitHub repo.

https://github.com/rails-api/active_model_serializers#maintenance-please-read

cll
  • 111
  • 5
5

That's because the serialization is not loaded by default in rails-api.
You have to do this:

class ApplicationController < ActionController::API
  include ::ActionController::Serialization
end
seoyoochan
  • 822
  • 3
  • 14
  • 28
1

I didn't downgrade, I spent some time trying different things and at the end I get to a pattern like this:

def sender
  if object.sender
    serializer = SenderSerializer.new(object.sender)
    ActiveModel::Serializer::Adapter::JsonApi.new(serializer).as_json[:senders]
  end
end

it's ugly but it did the trick for me.

For a has_many relation, you can do something like this:

def attachments
  attachments = object.attachments.to_a
  return [] if attachments.empty?
  serializer = ActiveModel::Serializer::ArraySerializer.new(attachments, each_serializer:AttachmentSerializer)
  ActiveModel::Serializer::Adapter::JsonApi.new(serializer).as_json[:attachments]
end
fsainz
  • 121
  • 1
  • 3