jsonapi-RB关系实例

问题描述:

我试图得到一个JSON它看起来像这样jsonapi-RB关系实例

{ 
    "data" : { 
    "type": "field_definition", 
    "id": 5, 
    "attributes": { 
     "specifier": "foo", 
     "entity_type": "bar" 
    } 
    "relationships": { 
     "active_collections" : [1,2,3] 
    } 
    } 
} 

我做了哪些im使用作为我的模型测试类:

class Test 
    attr_reader :id, 
       :specifier, 
       :entity_type, 
       :active_collections 

     def initialize 
     @id = 5 
     @specifier = "foo" 
     @entity_type = "bar" 
     @active_collections = [1,2,3] 
     end 
    end 

我的串行:

class SerializableFieldCollection < JSONAPI::Serializable::Resource 
    type 'field_collection' 

    attributes :specifier, :entity_type 

    has_many :active_collections 
end 

我打电话一切都像

def index 
    render jsonapi: Test.new, 
      class: SerializableFieldCollection, 
      status: 200 
    end 


{"data"=> 
    {"id"=>"5", "type"=>"field_collection", "attributes"=>{"specifier"=>"foo", "entity_type"=>"bar"}, "relationships"=>{"active_collections"=>{"meta"=>{"included"=>false}}}}} 

有人能指出我如何使用jsonapi-rb gem中的关系/ has_many函数的正确方向吗?

您是否验证过JSONAPI::Serializable::Resource implements ActiveModelActiveRecord?如果没有,我不认为你可以在这里使用has_many。你的定义在哪里ActiveCollection

+0

我想'JSONAPI :: Serializable接口:: Resource'都有自己impelementation不涉及'ActiveRecord'?根据'jsonapi-rails'提供的文档'has_many'是正确的使用 – Rhs

+0

链接文档http://jsonapi-rb.org/guides/serialization/defining.html – Rhs

+0

'has_many'确实是'JSONAPI :: Serializable :: Resource' DSL。 – beauby

我认为你的问题是关于{"meta"=>{"included"=>false}}的一部分,你宁愿是{"data"=>[{ "type": "foo", "id": "1" },{ "type": "foo", "id": "2" }, ...]}? 如果是这样,默认行为是仅当关系被包括时序列化关系的链接数据。为了在响应中包含关系,请使用include渲染器选项。

例子:

render jsonapi: Test.new, 
     class: SerializableFieldCollection, 
     include: 'active_collections', 
     status: 200