0

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

2
  • Could it be because of your .where? Docs say hash notation should look like this: User.where({ name: "Joe", email: "[email protected]" })
    – nolyoly
    Commented Jul 19, 2020 at 5:17
  • Did you throw a binding pry in there to see where exactly the undefined method error is occuring since you have .latitude in multiple places?
    – nolyoly
    Commented Jul 19, 2020 at 5:21

1 Answer 1

1

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]
)

Not the answer you're looking for? Browse other questions tagged or ask your own question.