Search code examples
ruby-on-railsjsonrubyactive-model-serializers

Pass variable from Controller to Serializer in Rails


I have this code in my Controller to get distance in meters from one location to another location:

range = Geocoder::Calculations.distance_between([lat,lng],[Model.location.lat,Model.location.lng])
rangeInMeters = range * 1000            
rangeRounded = rangeInMeters.round
rangeRounded = rangeRounded / 100 * 100

and I have this code in my serializer to give a nicer output for the json response like this:

class ModelSerializer < ActiveModel::Serializer
  attributes :id, :name, :address, :range

  def range
  // something
  end
end

How to get rangeRounded be read by ModelSerializer so in json response it would be like this:

{
        "id": 1,
        "name": "Name A",
        "address": "Address A",
        "range": 500
    },

Solution

  • If I understood correctly your model has location which has lat and lng. And you want to access these fields in your serializer method.

    You can access these fields using 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