2

I have two models related :

class Item < ActiveRecord::Base
  belongs_to :carousel
end

And

class Carousel < ActiveRecord::Base
  has_many :items
end

I trying to open API to carousels using the JSON API Resources gem, i need to show carousel attributes and some items attributes, something like this:

 {
   "data": [
     {
       "id": "1",
       "type": "carousels",
       "links": {
       "self": "http://localhost:3000/api/v1/carousels/1"
     },
     "attributes": {
       "name": "primary",
       "items": [
         {
           "title": "first item",   
           "file-url": "url",
           "index": 0
         },
         {
           "title": "second item",   
           "file-url": "url",
           "index": 1
         }
        ]
       }
     }
   ]
}

My carousel resource:

  module Api
    module V1
      class CarouselResource < JSONAPI::Resource
        immutable
        attributes :name, :items

        def self.records(options = {})
          user = options[:context][:current_user]
          user.carousels
        end
       end
     end
   end

My result:

  {
    "data": [
      {
         "id": "1",
         "type": "carousels",
         "links": {
           "self": "http://localhost:3000/api/v1/carousels/1"
        },
          "attributes": {
          "name": "primary",
          "items": [
            {
              "id": 3,
              "carousel_id": 1,
              "file": {
                "url": "url"
              },
              "title": "first item",
              "kind": 0,
              "index": 0,
              "created_at": "2017-02-23T10:31:53.592-03:00",
              "updated_at": "2017-03-01T10:30:52.533-03:00"
            },
            {
              "id": 5,
              "carousel_id": 1,
              "file": {
                "url": "url"
               },
              "title": "second item",
              "kind": 0,
              "index": 1,
              "created_at": "2017-03-01T10:30:07.011-03:00",
              "updated_at": "2017-03-01T10:30:07.011-03:00"
             }
          ]
        }
      }
    ]
  }
  • 1
    To play with json use `JSON Builder` or `ActiveModelSerializers`. – ashvin Mar 02 '17 at 12:34
  • Adding a little bit more help to what @ashvin said. Once you start playing with `ActiveModelSerializers`, you can create one for your items, that way, you can explicitly specify the code to use that serializer, and in that file you'll set which attributes you want to expose in the API. Good luck!. – fanta Mar 02 '17 at 14:51
  • Thanks for help !! I solve this overwriting the items in method with @model.items.as_json(only: [:title, :file, :index]) – Jhonatan Martins Mar 02 '17 at 17:56

0 Answers0