Skip to content

Respect distance units when ordering by distance #50

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions lib/activerecord-postgres-earthdistance/acts_as_geolocated.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ def within_radius(radius, lat, lng)

def order_by_distance(lat, lng, order = "ASC")
earth_distance = Utils.earth_distance(through_table_klass, lat, lng)
earth_distance = Arel::Nodes::Multiplication.new(
Utils.quote_value(1 / MILES_TO_METERS_FACTOR), earth_distance
) if distance_unit === :miles
joins(through_table).order(Arel.sql("#{earth_distance.to_sql} #{order}"))
end

Expand Down
13 changes: 13 additions & 0 deletions spec/act_as_geolocated_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,19 @@
context "when selecting distance" do
let(:current_location) { { lat: 52.229676, lng: 21.012229 } } # Warsaw
it { is_expected.to eq ["Amsterdam", 680.410076641856] }

context "and selecting distinct and ordering by distance" do
subject do
Place
.order_by_distance(current_location[:lat], current_location[:lng])
.selecting_distance_from(current_location[:lat], current_location[:lng])
.distinct
.first
.try { |p| [p.data, p.distance.to_f] }
end

it { is_expected.to eq ["Amsterdam", 680.410076641856] }
end
end

context "through table" do
Expand Down