我使用的是Rails 4.2.1和active_model_serializers 0.10.0.rc2
我是API的新手,选择了active_model_serializers,因为它似乎正在成为rails的标准(尽管我不反对使用RABL或另一个serializer)
我遇到的问题是,我似乎不能在多层次关系中包含各种属性.例如我有:
项目
class ProjectSerializer < ActiveModel::Serializer attributes :id,:name,:updated_at has_many :estimates,include_nested_associations: true end
和估计
class EstimateSerializer < ActiveModel::Serializer attributes :id,: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,: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,"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
所提出的解决方案之一是用调用嵌套属性的方法覆盖属性,但这似乎被认为是一个黑客,所以我想尽可能的避免它.
无论如何,一个例子说明如何处理这个或一般的API建议将是非常感激的.
解决方法
每个提交1426:
https://github.com/rails-api/active_model_serializers/pull/1426 – 和相关讨论,您可以看到json和属性序列化的默认嵌套是一个级别.
如果您希望默认深度嵌套,则可以在active_model_serializer初始值设置中设置配置属性:
ActiveModelSerializers.config.default_includes =’**’