2

I am using Rails to create APIs containing basic todo information: name, list, and items. I want it to return json format, to look something like this:

{
  "data": [
    {
      "type": "posts",
      "id": "1",
      "attributes": {
        "title": "JSON API is awesome!",
        "body": "You should be using JSON API",
        "created": "2015-05-22T14:56:29.000Z",
        "updated": "2015-05-22T14:56:28.000Z"
      }
    }
  ],
  "links": {
    "href": "http://example.com/api/posts",
    "meta": {
      "count": 10
    }
  }
}

^code from Active Serializer's Github.

When I look on my localhost http://localhost:3000/api/users/, it shows

[{"id":1,"username":"Iggy1","items":[{"id":1,"list_id":1,"name":"Wash dishes","completed":true},{"id":7,"list_id":1,"name":"Finish this assignment","completed":false}],"lists":[{"id":1,"name":"Important!","user_id":1,"permission":"private"},...

It is returning an array of hashes. I am sure I missed an important step when I was setting up my serializer. How can I reformat my array of hashes into JSON API format?

I've read getting started guide, rendering, and JSON API section but I still couldn't figure it out. I might have overlooked it.

Some of my codes:

app/serializers/user_serializer.rb

class UserSerializer < ActiveModel::Serializer
   attributes :id, :username#, :email
   has_many :items, through: :lists
   has_many :lists
end

app/controllers/api/users_controller.rb

   def index
     @users = User.all
     render json: @users, each_serializer: UserSerializer
   end

routes Rails.application.routes.draw do

  namespace :api, defaults: { format: :json } do

     resources :users do
       resources :lists
     end
  end
end

Let me know if I can clarify it better. Thanks!!

Iggy
  • 5,129
  • 12
  • 53
  • 87
  • 2
    Have you declared you want to use the JSON API adapter? Need to set `ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonApi` in your config. Instructions [here](https://github.com/rails-api/active_model_serializers/blob/master/docs/general/adapters.md#jsonapi) – chrismanderson Jul 30 '16 at 00:28
  • 1
    It worked! Thank you :). I didn't know where to put it before. – Iggy Jul 30 '16 at 03:50

2 Answers2

2

(Answer from comments)

To use the JSON API adapter, you need to declare you want to use it.

 ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonApi

As per the AMS readme.

chrismanderson
  • 4,603
  • 5
  • 31
  • 47
  • Read Me link is currently broken, this might help: https://github.com/rails-api/active_model_serializers#documentation – SMAG May 12 '20 at 22:43
0
ActiveModelSerializers.config.adapter = :json_api # Default: `:attributes`

from 0-10-stable documentation

However, this did not solve my problem. It was due to the Hash being nested as discussed in this SO post

SMAG
  • 652
  • 6
  • 12