trailblazer / roar

Parse and render REST API documents using representers.
http://www.trailblazer.to/gems/roar
MIT License
1.85k stars 138 forks source link

Error trying to parse jsonapi data #180

Closed mustela closed 8 years ago

mustela commented 8 years ago

Hi there!

I'm trying to parse the following json

{
   "data": {
      "type": "organizations",
      "attributes": {
         "name": "New org"
      }
   }
}

So I have an Organization Decorator

require "roar/json/json_api"
require "json"

class OrganizationDecorator < Roar::Decorator
  include Roar::JSON::JSONAPI
  type :organizations

  # attributes: {}
  property :id
  property :name

end

Organization is a rails model, and then I'm trying to parse it

OrganizationDecorator.prepare(Organization.new).from_json('{"data":{"type":"organizations", "attributes":{"name":"New org"}}}')

But I can't make it works, I keep getting: undefined method[]' for nil:NilClass`

["/usr/local/lib/ruby/gems/2.1.0/gems/roar-1.0.4/lib/roar/json/json_api.rb:50:in `from_hash'",
 "/usr/local/lib/ruby/gems/2.1.0/gems/roar-1.0.4/lib/roar/json/json_api.rb:131:in `from_hash'",
 "/usr/local/lib/ruby/gems/2.1.0/gems/representable-2.3.0/lib/representable/json.rb:35:in `from_json'",

What I'm doing wrong?

Thanks!

apotonick commented 8 years ago

Wrong Roar, and wrong Representable! :grimacing:

Get roar/master, I'll push 1.1 as soon as I get more feedback! :beers:

mustela commented 8 years ago

Great! Its partially working now because relathionships are not being loaded.

This is the json

{
  "data": {
    "type": "organization",
    "attributes": {
      "name": "New org",
      "description": "My org description"
    },
    "relationships": {
      "organization_type": {
        "data": { "type": "organization_type", "id": "5f7118bd-afd9-4943-a101-2d5d1b7e1143" }
      }
    }
  }
}

And the decorator

require "roar/json/json_api"
require "json"

class OrganizationDecorator < Roar::Decorator
  include Roar::JSON::JSONAPI
  type :organizations

  # attributes: {}
  property :id
  property :name

  # relationships
  has_one :organization_type, populator: ::Representable::FindOrInstantiate do
    type :organization_types

    property :id
    property :name
  end
end

And the result

#<Organization:0x007fc8993c6c20
 id: nil,
 name: "",
 logo_url: nil,
 website_url: nil,
 billing_user_id: nil,
 organization_type_id: nil,
 tags: nil,
 description: nil,
 social: {},
 founded: nil,
 slug: nil,
 created_at: nil,
 updated_at: nil,
 deleted_at: nil>

As you can see the organization type hasn't ben loaded organization_type_id: nil,

mustela commented 8 years ago

Its working now :), thanks!