我正在使用Place
模型处理Rails 5.2项目,该项目由Geocoder gem进行地理编码。
到目前为止,一切似乎都运行良好,除非我从控制器处理搜索运行Place.near("a valid location")
,我得到以下错误:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*, 6371.0 * 2 * ASIN(SQRT(POWER(SIN((-31.9575512 - places.latitude) * PI() / ' at line 1: SELECT COUNT(places.*, 6371.0 * 2 * ASIN(SQRT(POWER(SIN((-31.9575512 - places.latitude) * PI() / 180 / 2), 2) + COS(-31.9575512 * PI() / 180) * COS(places.latitude * PI() / 180) * POWER(SIN((115.9160093 - places.longitude) * PI() / 180 / 2), 2))) AS distance, MOD(CAST((ATAN2( ((places.longitude - 115.9160093) / 57.2957795), ((places.latitude - -31.9575512) / 57.2957795)) * 57.2957795) + 360 AS decimal), 360) AS bearing) FROM `places` WHERE (places.latitude BETWEEN -32.13741552118375 AND -31.777686878816255 AND places.longitude BETWEEN 115.7040152609056 AND 116.12800333909439 AND (6371.0 * 2 * ASIN(SQRT(POWER(SIN((-31.9575512 - places.latitude) * PI() / 180 / 2), 2) + COS(-31.9575512 * PI() / 180) * COS(places.latitude * PI() / 180) * POWER(SIN((115.9160093 - places.longitude) * PI() / 180 / 2), 2)))) BETWEEN 0.0 AND 20)
从Rails控制台执行时,这条确切的行完美地运行...
关于为什么差异会受到高度赞赏的任何想法。
放置模型
class Place < ApplicationRecord
...
geocoded_by :full_address
after_validation :geocode
reverse_geocoded_by :latitude, :longitude do |obj, results|
if geo = results.first
obj.place_id = geo.place_id
end
end
after_validation :reverse_geocode
def full_address
"#{title}, #{street_address}, #{suburb} #{state} #{zip}, #{country}"
end
...
end
SearchController
class SearchController < ApplicationController
def search
# places = Place.all
# places = places.where('title LIKE ?', "%#{params[:title]}%") if params[:title].present?
# places = places.near(params[:location]) if params[:location].present?
@places = Place.near("Perth, Western Australia")
# @places = places
end
end
自发布此问题以来,我发现调用.inspect
会在控制台和视图中打印完整的ActiveRecord :: Relation,两者(即:with {{ 1}}调用控制器),调用.near
会在控制台和视图中产生上述错误两者。我认为这改变了一些事情......
非常感谢任何帮助!
答案 0 :(得分:0)
似乎near
范围由地理编码宝石和Rails&#39;构建。对关系的计算并不能很好地发挥作用。
只需强制Rails加载关系,然后再调用其他方法,例如any?
或blank?
。
@places = Place.near("Perth, Western Australia").load
在您的视图中使用@places.size
代替@places.count
,因为size
不会触发其他数据库查询,但会在已经加载关系时返回元素数组