Skip to content

Distance column doesn't exist as soon as I want to do some calculations #1205

Open
@Kulgar

Description

@Kulgar

Hello,

Expected behavior

I am not sure if it is a bug... But I definitely need your help.
I am trying to order results with a calculation on distances, like this:

User.near([lat, lng], 60, :order => "distance - 100 * rating")

So that a user with a 5 star ratings at 500 meters will appear before a user with 0 star ratings at 300 meters.

Actual behavior

Unfortunately as soon as I add any calculations on the distance field, I get this error:

column "distance" doesn't exist

Even if I only do something like "distance - 5"

The generated SQL query is:

SELECT sitters.*, 6371.0 * 2 * ASIN(SQRT(POWER(SIN((48.6060508 - sitters.latitude) * PI() / 180 / 2), 2) + COS(48.6060508 * PI() / 180) * COS(sitters.latitude * PI() / 180) * POWER(SIN((2.3040542 - sitters.longitude) * PI() / 180 / 2), 2))) AS distance, MOD(CAST((ATAN2( ((sitters.longitude - 2.3040542) / 57.2957795), ((sitters.latitude - 48.6060508) / 57.2957795)) * 57.2957795) + 360 AS decimal), 360) AS bearing FROM "sitters" WHERE "sitters"."available" = $1 AND ("sitters"."birthday" IS NOT NULL) AND ("sitters"."address_id" IS NOT NULL) AND ("sitters"."phone" IS NOT NULL) AND ("sitters"."mangopay_id" IS NOT NULL) AND (birthday < '1999-07-21 18:36:56.799307') AND (sitters.latitude BETWEEN -539544.3575004383 AND 539641.5696020382 AND sitters.longitude BETWEEN -816038.7180184539 AND 816043.3261268538 AND (6371.0 * 2 * ASIN(SQRT(POWER(SIN((48.6060508 - sitters.latitude) * PI() / 180 / 2), 2) + COS(48.6060508 * PI() / 180) * COS(sitters.latitude * PI() / 180) * POWER(SIN((2.3040542 - sitters.longitude) * PI() / 180 / 2), 2)))) BETWEEN 0.0 AND '60000000')  ORDER BY distance - 5 * rating

I tested without distance:

User.near([lat, lng], 60, :order => "100 * rating")

This works fine.

Environment info

Geocoder version: 1.4.4
Rails version: 4.2.5

Maybe you will find another (better?) solution for what I want to do.
Any advice/thoughts/help will be appreciated.

But I still find this behaviour a little bit strange, as we should be able to do some operations on the distance field, shouldn't we?

Many thanks!
Kulgar

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions