Marco Sanfilippo Marco Sanfilippo - 2 months ago 9
Ruby Question

Namespacing API with Active Model Serializer

I need to namespacing API for a Rails based application.

I use

Active Model Serializer
but now I need to versioning my API.

How?

I have yet subdomain constraints. For API, I wish to have...

api.domain.com/v1/users/


with (for example)
:id
and
:name
for
User


api.domain.com/v2/users/


with (for example)
:id
:name
:ranking
for
User


So, how should I create different
Serializer
, one for each namespace?

And... Must I create different
Serializer
in different controllers or different files? How exactly?

Thanks to all.

UPDATE

Some code:

routes.rb


constraints subdomain: 'api', default: {format: 'json'} do #api.domain.com

#API V1
namespace :v1 do
#resources for v1
end

#API V1
namespace :v2 do
#resources for v2
end


I have in
controllers/v1/resource_controller.rb
with
module V1
and
render json: @list
that renders ALL information of the resource.

So, Rails is not calling my serializer placed in
serializers/v1/resource_serializer.rb

Answer

As suggested @Mirza Memic is better to specify also the serializer when call render json:

with each_serializer: TopModule::SubModule::CustomSerializer

otherwise we could get error (model_name or read_attribute_for_serialization) if is a collection (simply serializer: instead of each_serializer: ONLY if is a SINGLE object)

Of course controller must be "sub-foldered" for each module name, as suggested @JĂșlio Campos.

Comments