I have two models, users
and locations
with no connection to each other, both of them with latitude
and longitude
columns.
I need to query for all users
and all locations
within a given radius of each and group them by the locations
Practically, I need a set of results that groups the users
that have the same locations
within a certain radius of them
There will be enough users
that it would be impractical to simply iterate over them, so I'm looking for either a SQL or Rails way of selecting them
I am using the rails geocoder (https://github.com/alexreisner/geocoder)
Question was downvoted, but I'll post the answer I ended up on anyway
I had to do away with the geocoder gem since it didn't play well with plucks or selects and just use the equation manually, ended up using:
User.select("ARRAY_AGG(users.id) as user_list, (SELECT array(SELECT locations.id from locations WHERE (6371.0 * 2 * ASIN(SQRT(POWER(SIN((users.latitude - locations.latitude) * PI() / 180 / 2), 2) + COS(users.latitude * PI() / 180) * COS(locations.latitude * PI() / 180) * POWER(SIN((users.longitude - locations.longitude) * PI() / 180 / 2), 2)))) <= CAST(<whatever radius> AS float))) as location_list").group("location_list")