假设有两个表项目和进度,一个项目有多个进度(ont-to-many(:
class Project < ApplicationRecord
has_many :progresses
end
class Progress < ApplicationRecord
belongs_to :project
end
我定义ProjectSerializer如下:
class ProjectSerializer < ApplicationSerializer
attributes :title, :state, :tags # and so on
attribute :lateset_progress
def lateset_progress
object.progresses.order(created_at: :desc).first
end
end
此外,我在控制器中初始化我的串行器,如下所示:
def show
project = Project.find(params[:id])
resource = ActiveModelSerializers::SerializableResource.new(
project, key_transform: :camel_lower, adapter: :json)
render json: resource
end
问题是嵌套的lastest_progress不由序列化程序处理,并且使用下划线呈现所有属性。
真正的响应数据是:
{
"project": {
"id": 1,
"title": "a test title",
"tags": [
"tag-A",
"tag-B"
],
"latestProgress": {
"id": 45,
"details": "run run run",
"project_id": 1,
"created_at": "2018-07-10 04:14:59 UTC",
"updated_at": "2018-07-10 04:14:59 UTC"
}
}
}
您可以使用这样的东西:
class ProjectSerializer < ApplicationSerializer
...
has_many :progresses, key: :lateset_progress do
object.progresses.order(created_at: :desc).first
end
...
end
如果您需要自定义序列化程序类,您可以为它使用其他选项。例如:has_many :progresses, key: :lateset_progress, serializer: CustomProgressSerializer do ...
第二部分介绍key_transform。我不确定如何使用ActiveModelSerializers::SerializableResource
实例进行渲染,但我在文档中看到了一些示例,其中这些选项用于渲染方法渲染文档
从我自己来说,我会建议使用这个符号
json_data = ActiveModelSerializers::SerializableResource.new(project,
key_transform: :camel_lower, adapter: :json
).as_json
通过as_json
和fileds: [...]
选项,您可以管理属性列表,其工作方式类似于"only"。例如as_json(fields: [:id, :updated_at])
但需要小心:如果使用其他方式创建序列化程序对象,则参数的顺序可能会有所不同。
ProjectSerializer.new(project).as_json(nil, fields: [:id, :status])
所有所说的应该是版本0.10.x 的真相