0

可以说我有一个名为Vendor(id,name,lat,lon,created_at)的模型。 而我有一个查询,其中我发现供应商距离当前的经纬度。向ActiveModel Serializer添加一个额外的字段

查询 -

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,纬度,经度,名称,created_at,距离}。 因此,模型属性被附加,但我怎么能添加额外的字段/属性,即“距离”到序列化的散列?

回答

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?。如果方法存在并返回falsey值,则该属性不包含在输出中。

+0

这不是给我“距离“在json。 –

+0

@ palash-kulkarni:无法复制。适用于我。 –

+0

我也试过。但没有工作。我认为我们想要的选择查询中的额外属性为“距离”,而不是供应商模型的一部分。所以它没有被添加 –

0

你可以像下面

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 
相关问题