Rails 4.2.1
和active_model_serializers 0.10.0.rc2
我对API很陌生,选择了active_model_serializers
,因为它似乎正在成为Rails的标准(虽然我不排斥使用RABL
或其他序列化程序)我的问题是,我似乎无法在多层关系中包含各种属性。例如,我有: 项目
class ProjectSerializer < ActiveModel::Serializer
attributes :id,
:name,
:updated_at
has_many :estimates, include_nested_associations: true
end
和估计值
class EstimateSerializer < ActiveModel::Serializer
attributes :id,
:name,
:release_version,
:exchange_rate,
:updated_at,
:project_id,
:project_code_id,
:tax_type_id
belongs_to :project
belongs_to :project_code
belongs_to :tax_type
has_many :proposals
end
提案
class ProposalSerializer < ActiveModel::Serializer
attributes :id,
:name,
:updated_at,
:estimate_id
belongs_to :estimate
end
当我访问
/projects/1
时,上述内容会产生:{
"id": 1,
"name": "123 Park Ave.",
"updated_at": "2015-08-09T02:36:23.950Z",
"estimates": [
{
"id": 1,
"name": "E1",
"release_version": "v1.0",
"exchange_rate": "0.0",
"updated_at": "2015-08-12T04:23:38.183Z",
"project_id": 1,
"project_code_id": 8,
"tax_type_id": 1
}
]
}
然而,我想要它生成的是:
{
"id": 1,
"name": "123 Park Ave.",
"updated_at": "2015-08-09T02:36:23.950Z",
"estimates": [
{
"id": 1,
"name": "E1",
"release_version": "v1.0",
"exchange_rate": "0.0",
"updated_at": "2015-08-12T04:23:38.183Z",
"project": {
"id": 1,
"name": "123 Park Ave."
},
"project_code": {
"id": 8,
"valuation": 30
},
"tax_type": {
"id": 1,
"name": "no-tax"
},
"proposals": [
{
"id": 1,
"name": "P1",
"updated_at": "2015-08-12T04:23:38.183Z"
},
{
"id": 2,
"name": "P2",
"updated_at": "2015-10-12T04:23:38.183Z"
}
]
}
]
}
理想情况下,我还希望能够指定每个序列化器中包含哪些属性、关联以及这些关联的属性。我一直在查看AMS问题,似乎对于如何处理这个问题(或者是否真正支持这种功能)存在一些来回讨论,但我很难确定当前状态是什么。
- https://github.com/rails-api/active_model_serializers/issues/835
- https://github.com/rails-api/active_model_serializers/issues/968
- https://github.com/rails-api/active_model_serializers/issues/414
- https://github.com/rails-api/active_model_serializers/issues/444
提出的解决方案之一是通过重写属性并使用方法调用嵌套属性,但这似乎被认为是一种hack,所以如果可能的话,我想避免它。
无论如何,关于如何处理此问题的示例或一般API建议将不胜感激。