Skip to content
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

Selecting a record from a result queries the database again #123

Open
nesrual opened this issue May 27, 2017 · 0 comments
Open

Selecting a record from a result queries the database again #123

nesrual opened this issue May 27, 2017 · 0 comments

Comments

@nesrual
Copy link

nesrual commented May 27, 2017

Using Rails 5.1.1 and Ruby 2.3.3

2.3.3 :001 > locations = Location.by_distance(:origin => [37.792,-122.393])

This queries the database as expected:

  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]]

And we have an ActiveRecord_Relation:

2.3.3 :002 > locations.class
 => Location::ActiveRecord_Relation

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:

2.3.3 :004 > locations.first
 => #<Location id: 970, name: "9c28dcea-ef4f-4315-a07a-fb4cf2a5b6f4", lat: 99.665289316595, lng: 47.686835276217, distance: nil, created_at: "2017-05-27 05:55:56", updated_at: "2017-05-27 05:55:56">

What I don't quite understand is why the database is queried again? The result of locations ordered by distance is already fetched once.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant