1

我正在尝试使用地理编码器 gem 实现通过地理位置确定范围的方法。

我的目标是点击地理编码器 api,这将使我能够按到给定位置的距离过滤数据库中的条目,查询模型的地理编码经度和纬度数据,这是它在控制台中的工作方式:

Venue.near("Foobar Land")
=> [#<Venue:0x00007fd933bcf430
id: 266,
address: "Foobar Lane",
latitude: XXX.XXX,
longitude: XXX.XXX,

所以,我实现了以下范围:

场地.rb

class Venue < ApplicationRecord
  scope :location, -> address_search { near(address_search) }
end

但它抛出了这个错误:

PG::SyntaxError: ERROR:  syntax error at or near "AS"
LINE 1: ...- venues.longitude) * PI() / 180 / 2), 2))) AS distanc...
FULL SQL QUERY:
: SELECT COUNT(venues.*, 6371.0 * 2 * ASIN(SQRT(POWER(SIN((-37.8142176 - venues.latitude) * PI() / 180 / 2), 2) + COS(-37.8142176 * PI() / 180) * COS(venues.latitude * PI() / 180) * POWER(SIN((144.9631608 - venues.longitude) * PI() / 180 / 2), 2))) AS distance, MOD(CAST((ATAN2( ((venues.longitude - 144.9631608) / 57.2957795), ((venues.latitude - -37.8142176) / 57.2957795)) * 57.2957795) + 360 AS decimal), 360) AS bearing) FROM "venues" WHERE (venues.latitude BETWEEN -37.99408192118374 AND -37.634353278816256 AND venues.longitude BETWEEN 144.7354852795205 AND 145.1908363204795 AND (6371.0 * 2 * ASIN(SQRT(POWER(SIN((-37.8142176 - venues.latitude) * PI() / 180 / 2), 2) + COS(-37.8142176 * PI() / 180) * COS(venues.latitude * PI() / 180) * POWER(SIN((144.9631608 - venues.longitude) * PI() / 180 / 2), 2)))) BETWEEN 0.0 AND 20)

现在,我做了一大堆谷歌搜索,似乎 ActiveRecord 没有正确制定 SQL 查询存在已知问题。

此处已注意到此问题: https ://github.com/alexreisner/geocoder/issues/630

我可以通过执行此测试来重现它,运行 .count 方法,如该链接中所述:

a = Venue.near("paris")

a.class
=> Venue::ActiveRecord_Relation

a.count
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "AS"
LINE 1: ...- venues.longitude) * PI() / 180 / 2), 2))) AS distanc...
However the suggested solution in the article I linked to (adding (:all)), doesn't work for me:
a.count(:all)
(1.9ms)  SELECT COUNT(*) FROM "venues" WHERE (venues.latitude BETWEEN -37.99408192118374 AND -37.634353278816256 AND venues.longitude BETWEEN 144.7354852795205 AND 145.1908363204795 AND (6371.0 * 2 * ASIN(SQRT(POWER(SIN((-37.8142176 - venues.latitude) * PI() / 180 / 2), 2) + COS(-37.8142176 * PI() / 180) * COS(venues.latitude * PI() / 180) * POWER(SIN((144.9631608 - venues.longitude) * PI() / 180 / 2), 2)))) BETWEEN 0.0 AND 20)
ActiveRecord::StatementInvalid: PG::InFailedSqlTransaction: ERROR:  current transaction is aborted, commands ignored until end of transaction block

我不知道为什么我的 scopes 方法不起作用,但是当我也运行 .near("x").count 时似乎显然会抛出错误,所以我想如果我能解决这个问题,那么我可以也解决了我的范围问题。但是,提供附加参数 (:all),这是我可以在网上找到的唯一建议的解决方案,在我的情况下不起作用。

4

0 回答 0