Location Load (2.9ms) SELECT "locations".* FROM "locations" WHERE (locations.lat IS NOT NULL AND locations.lng IS NOT NULL) ORDER BY
(ACOS(least(1,COS(0.6595948309136971)*COS(-2.1361608313934197)*COS(RADIANS(locations.lat))*COS(RADIANS(locations.lng))+
COS(0.6595948309136971)*SIN(-2.1361608313934197)*COS(RADIANS(locations.lat))*SIN(RADIANS(locations.lng))+
SIN(0.6595948309136971)*SIN(RADIANS(locations.lat))))*3963.1899999999996)
ASC LIMIT $1 [["LIMIT", 11]]
Getting any record from the relation will query the database again:
2.3.3 :003 > locations.first
Location Load (3.2ms) SELECT "locations".* FROM "locations" WHERE (locations.lat IS NOT NULL AND locations.lng IS NOT NULL) ORDER BY
(ACOS(least(1,COS(0.6595948309136971)*COS(-2.1361608313934197)*COS(RADIANS(locations.lat))*COS(RADIANS(locations.lng))+
COS(0.6595948309136971)*SIN(-2.1361608313934197)*COS(RADIANS(locations.lat))*SIN(RADIANS(locations.lng))+
SIN(0.6595948309136971)*SIN(RADIANS(locations.lat))))*3963.1899999999996)
ASC LIMIT $1 [["LIMIT", 1]]
Fetching the record again will use a cached result:
Using Rails 5.1.1 and Ruby 2.3.3
This queries the database as expected:
And we have an ActiveRecord_Relation:
Getting any record from the relation will query the database again:
Fetching the record again will use a cached result:
What I don't quite understand is why the database is queried again? The result of locations ordered by distance is already fetched once.