Search code examples
ruby-on-railsrails-geocoder

Ordering posts by distance to city using geocoder


I am trying to order my posts by how close they are to the location of the current user using geocoder. Here is the controller:

def top
@city = request.location.city
@closepost = Post.near(@city, order: :distance)
end

and here is the view:

<% @closepost.each do |post| %>
 <%= post.title %>
<% end %>

I am getting this error:

undefined method `to_f' for {:order=>:distance}:Hash

Solution

  • in controller you define:

    @closepost

    while in view you are calling:

    @closeposts

    and you call .each on a variable that is not defined.

    update

    irb> a=Geokit::Geocoders::GoogleGeocoder.geocode '140 Market St, San Francisco, CA' 
    irb> a.ll 
    => 37.79363,-122.396116
    
    @closeposts = Post.within(5, :origin => @city.ll).order('distance DESC') 
    

    with geocode

    @closeposts = Post.near('dublin', 50, :order => :distance)
    

    You missed the distance parameter