我在我的控制器中有这个代码,以便从一个位置到另一个位置以米为单位:
range = Geocoder::Calculations.distance_between([lat,lng],[Model.location.lat,Model.location.lng])
rangeInMeters = range * 1000
rangeRounded = rangeInMeters.round
rangeRounded = rangeRounded / 100 * 100
我在序列化程序中有这个代码,为json响应提供更好的输出,如下所示:
class ModelSerializer < ActiveModel::Serializer
attributes :id, :name, :address, :range
def range
// something
end
end
如何获取rangeRounded可由ModelSerializer读取,因此在json响应中它将是这样的:
{
"id": 1,
"name": "Name A",
"address": "Address A",
"range": 500
},
答案 0 :(得分:0)
如果我理解正确,您的模型location
有lat
和lng
。并且您希望在序列化方法中访问这些字段。
您可以使用object.
RailsCasts - Active Model Serializers episode
#controller
def action
...
range = Geocoder::Calculations.distance_between([lat,lng],[Model.location.lat,Model.location.lng])
range_in_meters = range * 1000
range_rounded = range_in_meters.round
range_rounded = range_rounded / 100 * 100
...
render json: @model, serializer: ModelSerializer, range_rounded: range_rounded
end
#serializer
class ModelSerializer < ActiveModel::Serializer
attributes :id, :name, :address, :range
#point assosiations here (same as in model)
def range
puts @instance_options[:range_rounded]
end
end