0

大家好,我有一个小应用程序,它在停止模型上获取地址并通过地理编码器 gem 对其进行地理编码

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

  
end

这个停止模型属于旅行。我使用这些行为作为列表来给止损一个位置。

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

我想使用两站之间距离的位置。

我知道我可以使用 stop.trip 访问停靠站的行程,所以我想使用 stop.trip 通过下一个 stop.position 访问停靠站

所以一站会使用 Geocoder:: Calculations.distance_between 计算到下一站的距离,就像这样

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

不幸的是,当我这样做时,我得到

#Stop::ActiveRecord_AssociationRelation:0x00007fbab4e15cf0 的未定义方法“纬度”

所以我的问题是如何访问位置为 2 的当前行程站点的纬度

4

1 回答 1

1

您可以通过以下方式访问列表中的下一项:

stop.lower_item

所以:

next_stop = stop.lower_item

Geocoder::Calculations.distance_between(
  [stop.latitude, stop.longitude],
  [next_stop.latitude, next_stop.longitude]
)
于 2020-07-20T06:39:14.943 回答