jsonapi-rb 关系示例
jsonapi-rb Relationships Example
我正在尝试 JSON 看起来像这样
{
"data" : {
"type": "field_definition",
"id": 5,
"attributes": {
"specifier": "foo",
"entity_type": "bar"
}
"relationships": {
"active_collections" : [1,2,3]
}
}
}
我做了一个测试 class,我将其用作我的模型:
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 中使用 relationships/has_many 函数?
您是否已验证 JSONAPI::Serializable::Resource
实现了 ActiveModel
或 ActiveRecord
?如果不是,我认为您不能在此处使用 has_many
。您对 ActiveCollection
的定义在哪里?
我认为你的问题是关于 {"meta"=>{"included"=>false}}
部分,你更愿意成为 {"data"=>[{ "type": "foo", "id": "1" },{ "type": "foo", "id": "2" }, ...]}
?
如果是这样,默认行为是仅当包含关系时才序列化关系的链接数据。为了在响应中包含关系,请使用 include
渲染器选项。
示例:
render jsonapi: Test.new,
class: SerializableFieldCollection,
include: 'active_collections',
status: 200
我正在尝试 JSON 看起来像这样
{
"data" : {
"type": "field_definition",
"id": 5,
"attributes": {
"specifier": "foo",
"entity_type": "bar"
}
"relationships": {
"active_collections" : [1,2,3]
}
}
}
我做了一个测试 class,我将其用作我的模型:
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 中使用 relationships/has_many 函数?
您是否已验证 JSONAPI::Serializable::Resource
实现了 ActiveModel
或 ActiveRecord
?如果不是,我认为您不能在此处使用 has_many
。您对 ActiveCollection
的定义在哪里?
我认为你的问题是关于 {"meta"=>{"included"=>false}}
部分,你更愿意成为 {"data"=>[{ "type": "foo", "id": "1" },{ "type": "foo", "id": "2" }, ...]}
?
如果是这样,默认行为是仅当包含关系时才序列化关系的链接数据。为了在响应中包含关系,请使用 include
渲染器选项。
示例:
render jsonapi: Test.new,
class: SerializableFieldCollection,
include: 'active_collections',
status: 200