user2826911
user2826911

Reputation: 44

ActiveModel Serializer won't look up serializer class implicitly, to get json serialized correctly the serializer has to be explicitly passed

I'm having an issue in my Rails 4.2.6 project with ActiveModel Serializers (v0.10.2). The issue I'm having is if no serializer is passed to the render call in the controller, rails won't use any serializer and render the object as it would normally. However, passing it the serializer class name works as expected.

render json: @tag  # renders the whole object as if just to_json was called
render json: @tag, serializer: API::V1::TagSerializer # renders it correctly through the serializer

Currently, the controller this is in a versioned api namespace API::V1::Tags

I have a action_model_serializers initializer, and it's contents are:

ActiveModelSerializers.config.adapter = :json_api
ActiveModelSerializers.config.key_transform = :camel_lower
ActiveModelSerializers.config.serializer_lookup_enabled = true

And my serializer located in app/serializers/api/v1/tag_serializer.rb:

class API::V1::TagSerializer < ApplicationSerializer
  attributes :id, :name, :created_at, :updated_at

  has_many :taggings, serializer: API::V1::TaggingSerializer

  link :self do
    api_v1_tag_url(object, host: 'localhost:3000')
  end
end

I'm not quite sure what is wrong, I have tried restarting everything, I have included ActionController::Serialization in my application controller, nothing I try works.

Unsure if this is a related problem, but even after added include: 'taggings' to the render function, and the has_many :taggings, serializer: API::V1::TaggingSerializer in the serializer, the only thing being rendered in the relationships is the tagging id and type: 'taggings'

Upvotes: 0

Views: 1029

Answers (1)

user2420206
user2420206

Reputation:

I had the same problem , and I was also doing name spacing. I think this answer and comments are still relevant

As I really did want to namespace my serializers (api:v1) so I could swap in new serializers in the next version, I just kept the explicit call. If there is a better answer I would love to hear about it

Upvotes: 0

Related Questions