Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

active model serializer not working with rails-api gem

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

like image 739
Gagan Avatar asked Nov 05 '14 02:11

Gagan


3 Answers

In your BaseController, did you add the include bellow ?

include ActionController::Serialization

like image 146
Edouard Brèthes Avatar answered Oct 31 '22 17:10

Edouard Brèthes


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

like image 31
cll Avatar answered Oct 31 '22 18:10

cll


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
like image 5
seoyoochan Avatar answered Oct 31 '22 16:10

seoyoochan