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
In your BaseController, did you add the include bellow ?
include ActionController::Serialization
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With