我试图在 Rails 应用程序中使用空间距离,但当我尝试使用 order 方法时,我不断遇到“ActiveRecord::UnknownAttributeReference: 使用非属性参数调用的查询方法”错误。
这是我的代码:
def nearby_locations
third_party_location_query = ThirdPartyLocation.where(id: id).select('geom').to_sql
third_party.organisation.locations.active.
select("locations.*, ROUND(ST_DistanceSphere(locations.geom, (#{third_party_location_query}))::numeric, 0)::integer distance").
order("locations.geom <-> (#{third_party_location_query})").
limit(10).as_json(methods: [:distance])
end
Run Code Online (Sandbox Code Playgroud)
我知道该错误是由于将非属性值传递给 order 方法而引起的,但我不确定在这种情况下如何避免它。如何在查询中使用空间距离而不会遇到此错误?