我有一个用户在高度模型中记录了许多高度(身高测量值),但只想序列化最后一个高度。
我试图创建一个(假的)自定义 has_one 关联,但它没有给我我想要的东西......
应用程序/序列化程序/user_serializer.rb
class UserSerializer < BaseSerializer
attributes :email
# has_many :heights
has_one :current_height, record_type: :height do |user|
user.heights.last
end
end
应用程序/控制器/users_controller.rb
options[:include] = [:heights]
render json: UserSerializer.new(user, options).
照原样,我得到了错误:"heights is not specified as a relationship on UserSerializer."
如果我取消注释# has_many :heights
,我会得到:
{
"data": {
"id": "1",
"type": "user",
"attributes": {
"email": "fake@email.com"
},
"relationships": {
"heights": {
"data": [
{
"id": "1",
"type": "height"
},
{
"id": "2",
"type": "height"
}
]
},
"currentHeight": {
"data": {
"id": "2",
"type": "height"
}
}
}
},
"included": [
{
"id": "1",
"type": "height",
"attributes": {
"value": "186.0"
}
},
{
"id": "2",
"type": "height",
"attributes": {
"value": "187.0"
}
}
]
}
但我不想在复合文档中包含所有记录的高度......
预期结果
{
"data": {
"id": "1",
"type": "user",
"attributes": {
"email": "fake@email.com"
},
"relationships": {
"currentHeight": {
"data": {
"id": "2",
"type": "height"
}
}
}
},
"included": [
{
"id": "2",
"type": "height",
"attributes": {
"value": "187.0"
}
}
]
}