1

我有一个用户在高度模型中记录了许多高度(身高测量值),但只想序列化最后一个高度。

我试图创建一个(假的)自定义 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"
            }
        }
    ]
}
4

2 回答 2

0

您可以将其添加到User模型中

has_one :last_height, -> { order 'created_at DESC' }, class_name: "Height"
于 2019-08-18T08:19:02.210 回答
0

如果我指责你想多了,请原谅我,但你不能给你的用户添加一个方法来获得最后一个高度吗?

class User < ApplicationRecord
  #
  # your user code here
  # ...

  def last_height
    self.heights.last
  end
end

然后获取记录current_user.last_height

如果这不是您要的,我很抱歉,我可能没有完全理解这个问题。

于 2019-08-16T21:27:49.190 回答