如何使用geokit-rails根据Location表radius字段查询范围内地点?
使用geokit-rails按动态半径查询位置的问题
我们使用geokit-rails gem实现“查找距离指定地点一定范围内的所有位置”功能,数据库迁移及模型代码如下:
class CreateLocations < ActiveRecord::Migration[7.2] def change create_table :locations do |t| t.decimal :lat t.decimal :lng t.float :radius end end end class Location < ApplicationRecord acts_as_mappable end
以下代码可以正确返回坐标(37,-122)周边5英里范围内的所有位置:
Location.within(5, origin: [37,-122])
但我们需要根据Location表中radius字段存储的动态距离来查询范围内的位置,以下代码无法正常运行:
Location.within('locations.radius', origin: [37,-122])
请问问题出在哪里?
解决方案更新
@max和@engineersmnky提供的解决方案效果很好。另外我还发现可以用merge函数实现关联表的.within查询,比如当Location关联多个Product时,要查询位于配送范围内的地点所售卖的所有产品,可使用以下代码:
Product.joins(:location).merge(Location.within(Location.arel_table[:radius], origin: [37, -122]))
内容的提问来源于stack exchange,提问作者vince
相关产品推荐
相关产品推荐

