在 Rails 中将变量从 Controller 传递到 Serializer

Pass variable from Controller to Serializer in Rails

我的控制器中有这段代码,用于获取从一个位置到另一个位置的距离(以米为单位):

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
    },

如果我理解正确的话,您的模型有 location,其中有 latlng。并且您想在序列化程序方法中访问这些字段。

您可以使用 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