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

时间:2018-01-18 11:41:35

标签: ruby-on-rails json ruby active-model-serializers

我在我的控制器中有这个代码,以便从一个位置到另一个位置以米为单位:

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

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您的模型locationlatlng。并且您希望在序列化方法中访问这些字段。

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