【问题标题】:Add a extra field to ActiveModel Serializer向 ActiveModel 序列化程序添加一个额外的字段
【发布时间】:2017-08-02 06:06:15
【问题描述】:

假设我有一个名为 Vendor(id, name, lat, lon, created_at) 的模型。 我有一个查询,我在其中找到供应商与当前纬度和经度的距离。

查询是 -

query = "*, ST_Distance(ST_SetSRID(ST_Point(#{lat}, #{lon}), 4326)::geography,ST_SetSRID(ST_Point(lat, lon), 4326)::geography) as distance"

Vendor.select(query)

我的序列化程序类为 -

class VendorSerializer < ActiveModel::Serializer
    attributes :id,
               :lat,
               :lon,
               :name,
               :created_at

    def attributes
        hash = super
        # I tried to override attributes and added distance but it doesn't add
        hash[:distance] = object.distance if object.distance.present?
        hash
    end
end

我想要一个序列化的对象作为 {id, lat, lon, name, created_at, distance}。 所以模型属性被附加,但我如何添加额外的字段/属性,即“距离”到序列化哈希?

【问题讨论】:

  • 您找到解决方案了吗?

标签: ruby-on-rails ruby postgresql activerecord active-model-serializers


【解决方案1】:

AMS 对此具有内置支持。不需要肮脏的黑客攻击。

class VendorSerializer < ActiveModel::Serializer
  attributes :id, :lat, :lon, :name, :created_at,
             :distance, :foobar


  def include_distance?
    object.distance.present?
  end

  def foobar
    'custom value'
  end

  def include_foobar?
    # ...
  end
end

对于每个属性,AMS 都会尝试查找并调用方法include_ATTR?。如果该方法存在并返回 false 值,则该属性不包含在输出中。

【讨论】:

  • 这不是在 json 中给我“距离”。
  • @palash-kulkarni:无法复制。为我工作。
  • 我也试过这个。但是没有用。我认为我们在选择查询中想要并拥有的额外属性是“距离”,它不是供应商模型的一部分。所以它没有被添加
  • @palash-kulkarni:啊,可能是这样。在这种情况下,确实,序列化供应商似乎没用。您可以绕过所有事情(创建供应商并对其进行序列化)并直接输出您的结果集。
  • 如果有人想要所有其他属性以及额外的字段,它怎么会没用?
【解决方案2】:

你可以这样做

class VendorSerializer < ActiveModel::Serializer
    attributes :id,
               :lat,
               :lon,
               :name,
               :created_at,
               :some_extra_attribute

    def some_extra_attribute
      object.some_extra_attribute # Or any other calculation inside this method
    end


end

【讨论】:

  • 否决,bcoz 没有解释如何使用此方法some_extra_attribute
  • Rails API 与此有什么关系?在您回答的任何地方都没有提到我如何从这个序列化中调用这个some_extra_attribute 方法,或者我如何在我的回复中包含这个some_extra_attribute 方法的结果。它会自动附加到序列化的 json 中吗?因为那没有发生。
  • 其实有提到。如果您查看第 2 行,attributes :id, :lan, :etc,这就是 rails 知道将哪些属性序列化为响应的方式。你不需要显式调用任何方法,rails 会为你做 至于 rails api - 你需要知道 railse 类的接口才能使用它们,所以我鼓励你去阅读 rails 中的序列化程序是什么以及如何工作以停止根据自己有限的知识做出错误的决定
【解决方案3】:

以下是活动模型序列化程序的指南: Active Model Serializer Guide

您的问题的解决方案在这里定义: Active Model Serializer Guide - Serializer

【讨论】:

  • 仅链接的答案不是很有用。在答案本身中包含链接文章的相关部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多