All threads / Pass variable from Controller to Serializer in Rails

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Pass variable from Controller to Serializer in Rails

Rony Fhebrian asked 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
    },
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 37,629+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.