ruby-on-railsacts-as-list

Rails Access Geocoder::Calculations


Hi All I have a little app that takes an address on the stop model and geo codes it via geocoder gem

class Stop < ApplicationRecord
  belongs_to :trip
  acts_as_list scope: :trip
  after_validation :geocode
  geocoded_by :address

  
end

This stop model belongs to a trip. I use the acts as list to give the stop a position.

class Trip < ApplicationRecord
  belongs_to :user
  has_many :stops, -> { order(position: :asc) }
end

I want to use the position of the distance between two stops.

I know I can access the trip through the stop by using stop.trip so I want to use the stop.trip to access the stop with the next stop.position

So stop one would calculate the distance to the next stop using the Geocoder:: Calculations.distance_between like so

  Geocoder::Calculations.distance_between([ stop.latitude, stop.longitude], [ stop.trip.stops.where(position: 2).latitude, stop.trip.stops.where(position: 2).longitude])

Unfortunately, when I do this I get

undefined method `latitude' for #Stop::ActiveRecord_AssociationRelation:0x00007fbab4e15cf0

So my question is how do I access the latitude of the current trips stop with position of 2


Solution

  • You can access the next item in the list with:

    stop.lower_item
    

    so:

    next_stop = stop.lower_item
    
    Geocoder::Calculations.distance_between(
      [stop.latitude, stop.longitude],
      [next_stop.latitude, next_stop.longitude]
    )