0

I'm using the gem 'active_model_serializers' version 0.9.3. I will minimize my model for simplicity. I have a Center model with attributes id, title and a CenterSerializer, and also CentersCollectionSerializer.

Now my question is when I instantiate from CenterSerializer to serialize a single center and call to_json on the instante i get this:

CenterSerializer.new(Center.first).to_json
"{\"center\":{\"title\":\"ExampleTitle\"}}"

which is what I should get cause i have to have the root node. The same response is returned when make curl request to the show action of the specific center. I get accepted behavior when i make a curl request to the index action of the centers getting a json response:

"{\"centers\":[
{\"title\":\"ExampleTitle\"},
{\"title\":\"ExampleTitle2\"},
{\"title\":\"ExampleTitle3\"}
}]"

But if i do

CentersCollectionSerializer.new(Center.all).to_json

i get the same thing but without the root node:

    "[{\"title\":\"ExampleTitle\"},
    {\"title\":\"ExampleTitle2\"},
    {\"title\":\"ExampleTitle3\"}}]"

What am I doing wrong and what is happening, that he explicit to_json call on an array serializer instance gives response without root node, and the request to the index action using

respond_with @centers

(with responders gem) or

render json: @centers

gets the response with the root node?

Vlatko Ristovski
  • 111
  • 1
  • 11
  • Please check the content of `@centers` - it may be a hash and hence you get the output that you are seeing. – Wand Maker Dec 29 '15 at 15:30
  • I think you can pass root name in the call CentersCollectionSerializer.new(Center.all, root: 'centers').to_json – mandar.gokhale Dec 29 '15 at 15:33
  • @WandMaker Nope, it's an ActiveRecord::Relation object. `@centers = Center.all` – Vlatko Ristovski Dec 29 '15 at 15:34
  • @madyrockss Yes, I know this will work I've dig into the active_model_serializers gem . But I'm not passing anything in the options hash in the Controller which uses the same serializer class to render json response. All I do is `render json: @centers, serializer: CentersCollectionSerializer` – Vlatko Ristovski Dec 29 '15 at 15:40
  • What is the name of controller? "centers" is most likely plural form of controller as per my tests – Wand Maker Dec 29 '15 at 19:55
  • @WandMaker sorry I might not understand you properly but the name of the controller class is CentersController if that is your question – Vlatko Ristovski Dec 30 '15 at 09:03
  • @VlatkoRistovski When I was testing with a `WelcomeController`, the URL had word `welcome/index` in it - and I noticed that JSON used `welcome` as root name - hence, I feel that the serializer gem may be using controller name as derived from URL – Wand Maker Dec 30 '15 at 09:05

0 Answers0