Reputation:
I'm trying to get two attributes from:
<% for location in @trip.locations %>
<%= location.address %>
<% end %>
and put them in the method to calculate distance between them:
<% @distance = Geocoder::Calculations.distance_between(address1, address2) %>
I was trying to use f.e @trip.locations.first(1) but I was receiving only the first letter of these two adresses and I couldn't fit in in method (wrong number of arguments - 1 for 2)
I'd appreciate any help.
Upvotes: 0
Views: 33
Reputation: 36880
You can loop through the locations, tracking the last location so you have it for calculating distance with the current location.
<% 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 %>
But this is a lot of code for a view... I'd be tempted to do the calculations in the controller to create a distance array for the view.
Upvotes: 0
Reputation: 52367
<% @trip.locations.each do |location| %>
<%= location.address %>
<% end %>
This will iterate over all @trip
's locations and print them out.
In Ruby you don't use for loops. Read about iterators in Ruby.
To get first location from @trip
you would do:
@trip.locations.first
To get last location:
@trip.locations.last
Calculate the distance between these two:
<% @distance = Geocoder::Calculations.distance_between(@trip.locations.first, @trip.locations.last) %>
Upvotes: 1