我有以下查询,这要归功于gem geocoder:
@places = Place.near(coords, radius)
查询的SQL形式如下:
Place Load (20.9ms) SELECT places.*, 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((41.3828939 - places.latitude) * PI() / 180 / 2), 2) + COS(41.3828939 * PI() / 180) * COS(places.latitude * PI() / 180) * POWER(SIN((2.1774322 - places.longitude) * PI() / 180 / 2), 2))) AS distance, MOD(CAST((ATAN2( ((places.longitude - 2.1774322) / 57.2957795), ((places.latitude - 41.3828939) / 57.2957795)) * 57.2957795) + 360 AS decimal), 360) AS bearing FROM "places" WHERE (places.latitude BETWEEN 41.31052800844458 AND 41.45525979155542 AND places.longitude BETWEEN 2.080984013859067 AND 2.273880386140933 AND (3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((41.3828939 - places.latitude) * PI() / 180 / 2), 2) + COS(41.3828939 * PI() / 180) * COS(places.latitude * PI() / 180) * POWER(SIN((2.1774322 - places.longitude) * PI() / 180 / 2), 2)))) BETWEEN 0.0 AND 5)
ORDER BY distance ASC
它在查询末尾按距离排序。很好,但是现在我想按字母顺序对元素进行排序,所以我要遵循查询
@places = @ places.order(名称::asc)
但是此查询返回为SQL:
Place Load (1.7ms) SELECT places.*, 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((41.3828939 - places.latitude) * PI() / 180 / 2), 2) + COS(41.3828939 * PI() / 180) * COS(places.latitude * PI() / 180) * POWER(SIN((2.1774322 - places.longitude) * PI() / 180 / 2), 2))) AS distance, MOD(CAST((ATAN2( ((places.longitude - 2.1774322) / 57.2957795), ((places.latitude - 41.3828939) / 57.2957795)) * 57.2957795) + 360 AS decimal), 360) AS bearing FROM "places" WHERE (places.latitude BETWEEN 41.31052800844458 AND 41.45525979155542 AND places.longitude BETWEEN 2.080984013859067 AND 2.273880386140933 AND (3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((41.3828939 - places.latitude) * PI() / 180 / 2), 2) + COS(41.3828939 * PI() / 180) * COS(places.latitude * PI() / 180) * POWER(SIN((2.1774322 - places.longitude) * PI() / 180 / 2), 2)))) BETWEEN 0.0 AND 5)
ORDER BY distance ASC, "places"."name" ASC
到目前为止,我尝试将结果存储在新变量中,但随后得到以下提示:
CACHE Place Load (0.1ms) SELECT places.*, 3958.755864232 * 2 * A etc.
我知道查询已被缓存。
我也阅读了文档,但是他们谈论引擎,所以我很难理解。
https://edgeguides.rubyonrails.org/caching_with_rails.html
有人可以指导我解决这个问题吗?我想了解一下,为什么要拥有AR集合并应用方法,为什么要再次使用上一个查询,而不是仅将其应用于元素。
我如何按字母顺序对元素进行排序,而忽略按距离排序?
我不知道如何避免宝石按距离排序。我想按字母顺序排序。