4

I know how to use the near method to get all results within a certain radius, but how do I get all results and order by distance?

I know I could do something like this:

Location.near(my_location, 999999, order: 'distance')

However, I would rather skip the radius check altogether and simply get all results sorted by distance.

Godwin
  • 9,739
  • 6
  • 40
  • 58
  • Hey, @Godwin. If you felt like my answer solved your problemm, consider marking it as the solution. Also so this doesn't appear on the non-answered lists. Thanks. – ekampp Aug 04 '15 at 12:34

1 Answers1

5

I have had the same issue, and I ended up adding this scope to my geocoded class:

class A
  extend Geocoder::Model::ActiveRecord
  reverse_geocoded_by :latitude, :longitude

  scope :with_distance_to, ->(point) { select("#{table_name}.*").select("(#{distance_from_sql(point)}) as distance") }
end

This will allow you to do A.with_distance_to(point).order('distance')

ekampp
  • 1,904
  • 18
  • 31
  • its giving error http://stackoverflow.com/questions/33244132/pgsyntaxerror-at-error-syntax-error-at-or-near-rails/33266036#33266036 – Adt Oct 22 '15 at 07:57