我正试图从以下两个属性中获取:
<% for location in @trip.locations %>
<%= location.address %>
<% end %>
并将它们放入方法中以计算它们之间的距离:
<% @distance = Geocoder::Calculations.distance_between(address1, address2) %>
我试图使用fe @ trip.locations.first(1),但我只收到这两个地址的第一个字母,我无法使用方法(错误的参数数量 - 1表示2)< / p>
我很感激任何帮助。
答案 0 :(得分:1)
<% @trip.locations.each do |location| %>
<%= location.address %>
<% end %>
这会迭代所有@trip
的位置并打印出来。
在Ruby中,你不能使用for循环。阅读Ruby中的迭代器。
要获得@trip
的第一个位置,您可以这样做:
@trip.locations.first
获取最后位置:
@trip.locations.last
计算这两者之间的距离:
<% @distance = Geocoder::Calculations.distance_between(@trip.locations.first, @trip.locations.last) %>
答案 1 :(得分:0)
您可以遍历各个位置,跟踪最后一个位置,以便计算与当前位置的距离。
<% last_location_address = nil %>
<% @trip.locations.each do |location| %>
<% if last_location_address
<% distance = Geocoder::Calculations.distance_between(last_location_address, location.address) %>
<%= distance # this line outputs the distance %>
<% end %>
<% last_location_address = location.address %>
<% end %>
但这是视图的很多代码......我很想在控制器中进行计算,为视图创建一个距离数组。