pal*_*rni 5 ruby postgresql activerecord ruby-on-rails active-model-serializers
假设我有一个名为 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)
Run Code Online (Sandbox Code Playgroud)
我的序列化器类为 -
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
Run Code Online (Sandbox Code Playgroud)
我想要一个序列化对象为 {id, lat, lon, name,created_at,distance}。因此,模型属性被附加,但我如何添加额外的字段/属性,即“距离”到序列化哈希?
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
Run Code Online (Sandbox Code Playgroud)
对于每个属性,AMS都会尝试查找并调用方法include_ATTR?。如果该方法存在并返回 false 值,则该属性不包含在输出中。