2017-08-09 83 views
1

我試圖得到一個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函數的正確方向嗎?

回答

0

您是否驗證過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

1

我認爲你的問題是關於{"meta"=>{"included"=>false}}的一部分,你寧願是{"data"=>[{ "type": "foo", "id": "1" },{ "type": "foo", "id": "2" }, ...]}? 如果是這樣,默認行爲是僅當關系被包括時序列化關係的鏈接數據。爲了在響應中包含關係,請使用include渲染器選項。

例子:

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