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 
相關問題