trailblazer / roar-jsonapi

JSON API support for Roar.
http://trailblazer.to/gems/roar/jsonapi.html
MIT License
42 stars 18 forks source link

JSON API Serialize deep relationships #2

Closed myabc closed 7 years ago

myabc commented 7 years ago

From @wuarmin on September 27, 2016 17:49

I know JSON API module is not finished yet, but maybe this can be accomplished with less effort. In my opinion the serialized compound doc, generated from following code, should contain the ressource object (type: organisations, id: 8) in the included-payload.

require 'roar/json'
require 'roar/decorator'
require 'roar/json/json_api'

class ArticleDecorator < Roar::Decorator
  include Roar::JSON::JSONAPI
  type :articles

  property :id
  property :title

  has_one :author, class: Authors do
    type :authors

    property :id
    property :email

    has_one :organisation, class: Organisations do
      type :organisations

      property :id
      property :name
    end
  end

end

organisation = Organisations.new(id: 8, name: 'Articles23')
author = Authors.new(id: 4711, email: 'author@test.com', organisation: organisation)
article = Articles.new(id: 1, author: author, title: 'Programming')

puts ArticleDecorator.new(article).to_json

The result json contains the relationship, but the ressource-object is missing:

{
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "Programming"
    },
    "relationships": {
      "author": {
        "data": {
          "type": "authors",
          "id": "4711"
        }
      }
    }
  },
  "included": [
    {
      "type": "authors",
      "id": "4711",
      "attributes": {
        "email": "author@test.com"
      },
      "relationships": {
        "organisation": {
          "data": {
            "type": "organisations",
            "id": "8"
          }
        }
      }
    }
  ]
}

best regards

Copied from original issue: trailblazer/roar#200

myabc commented 7 years ago

@franzliedke not sure if this issue is still relevant for you, but if it is, I'd appreciate feedback on this fix.

franzliedke commented 7 years ago

@myabc Oh, sorry, I was still planning to get back to you on #12...

I am currently not using this library anymore (although it's good to know that progress is being made in this area), but from what I can tell (by glancing at the tests), this looks nice. :)

myabc commented 7 years ago

@franzliedke thanks for getting back! (and apologies, I just tagged you on the wrong issue)

myabc commented 7 years ago

@wuarmin not sure if this issue is still relevant for you, but if it is, I'd appreciate feedback on this fix.

wuarmin commented 7 years ago

@myabc Thank you. It looks nice. I'll test it on my side.

wuarmin commented 7 years ago

@myabc It works as expected. We'll discuss internally to switch to roar-jsonapi. I don't see a reason why not.