Ruby on rails Rails序列化-fast_jsonapi/active_model_序列化程序
我对使用fast_jsonapi/active_model_序列化程序构建API有点迷茫。我已经记下了基础知识,但似乎还停留在自定义解决方案上 我将此作为序列化程序:Ruby on rails Rails序列化-fast_jsonapi/active_model_序列化程序,ruby-on-rails,json,serialization,fastjsonapi,Ruby On Rails,Json,Serialization,Fastjsonapi,我对使用fast_jsonapi/active_model_序列化程序构建API有点迷茫。我已经记下了基础知识,但似乎还停留在自定义解决方案上 我将此作为序列化程序: class AreaSerializer include FastJsonapi::ObjectSerializer attributes :id, :name, :cost_center, :notes has_many :children end 在我的区域模型中,我有: has_many :children
class AreaSerializer
include FastJsonapi::ObjectSerializer
attributes :id, :name, :cost_center, :notes
has_many :children
end
在我的区域模型中,我有:
has_many :children, -> { Area.where(ancestry: id) }
我的控制器看起来像:
class Api::V1::AreasController < ApiController
def index
render json: AreaSerializer.new(Area.root).serialized_json
end
end
}
我正在寻找一个这样的输出:
{
"data": [{
"id": "1",
"type": "area",
"attributes": {
"id": 1,
"name": "Calgary",
"cost_center": "123456",
"notes": ""
},
"relationships": {
"areas": {
"data": [{
"id": "3",
"type": "area",
"attributes": {
"id": 3,
"name": "Child Area",
"cost_center": "123456",
"notes": ""
}
}]
}
}
}, {
"id": "2",
"type": "area",
"attributes": {
"id": 2,
"name": "Edmonton",
"cost_center": "78946",
"notes": ""
}
}]
}
其思想是嵌套关系显示细节等。我刚开始在rails项目中使用
fast\u jsonapi
fast\u jsonapi
遵守
因此,您将无法使用relationship helper函数(:has_many,:belling_to)来实现所需的输出,即将区域的属性嵌套在relationships
键中
"relationships": {
"areas": {
"data": [{
"id": "3",
"type": "area",
"attributes": { // nesting attributes of area
"id": 3,
"name": "Child Area",
"cost_center": "123456",
"notes": ""
}
}]
}
}
JSON:API指定:
为了减少HTTP请求的数量,服务器可能允许响应
包括相关资源以及请求的主要资源
资源。这种答复称为“复合文件”
因此,取而代之的是,在一个名为included
的键中有area
的属性
为了在响应中包含键
,您需要在控制器中向序列化程序提供选项
散列
我不太了解您的模型区域
关系,但假设一个区域
有许多子区域
class Api::V1::AreasController < ApiController
def index
// serializer options
options = {
include: [:sub_area],
collection: true
}
render json: AreaSerializer.new(Area.root, options).serialized_json
end
end
class Api::V1::AreasController
您不能在fast\u jsonapi中使用关联。以嵌套格式获取响应。您需要添加方法并需要创建另一个序列化程序
class AreaSerializer
include FastJsonapi::ObjectSerializer
set_type 'Area'
attributes :id, :name, :cost_center, :notes
attribute :childrens do |area, params|
ChildrenSerializer.new(area.childrens, {params:
params})
end
end
class ChildrenSerilizer
include FastJsonapi::ObjectSerializer
set_type 'Area'
attributes :id, :name ...
end
我开始使用上面列出的技术,但最终分叉并重新编写了jsonapi序列化程序gem,因此它允许嵌套(最多4层),并取消了具有
关系和属性键的概念。我还感到沮丧的是,它只输出ID和类型键,而这些类型在大多数情况下是冗余的,因为对象通常在数组中保持同一个类作为示例,并且人们很少使用真正的多态性(尽管它仍然支持这一点,并为多态关系输出ID/类型)
我重写的最好部分可能是,它允许通过一个新的字段
输入在json密钥树中的任意位置进行确定性字段选择
class AreaSerializer
include FastJsonapi::ObjectSerializer
set_type 'Area'
attributes :id, :name, :cost_center, :notes
attribute :childrens do |area, params|
ChildrenSerializer.new(area.childrens, {params:
params})
end
end
class ChildrenSerilizer
include FastJsonapi::ObjectSerializer
set_type 'Area'
attributes :id, :name ...
end