我已经尝试过其他问题的解决方案,但仍然遇到麻烦。我似乎也找不到是否有调试查询的好方法,因此我只能使用反复试验。
我正在Service
上创建一个示波器。
我的Service
与`会员有可选的belongs_to
关系:
class Service < ApplicationRecord
belongs_to :affiliate, optional: true
end
[Service
也有lonlat
列:
create_table "services", force: :cascade do |t|
t.bigint "affiliate_id"
t.geography "lonlat", limit: {:srid=>4326, :type=>"st_point", :geographic=>true}
t.index ["affiliate_id"], name: "index_services_on_affiliate_id"
t.index ["lonlat"], name: "index_services_on_lonlat", using: :gist
end
我的Affiliate
与belongs_to
之间具有AffiliatePlan
关系:
class Affiliate < ApplicationRecord
belongs_to :affiliate_plan
end
我的AffiliatePlan
有radius_miles
列:
create_table "affiliate_plans", force: :cascade do |t|
t.decimal "radius_miles"
end
鉴于经度和纬度,我的目标是从坐标中找到AffiliatePlan
半径以内的所有服务。
这是我在Service
课程中的最新尝试:
scope :within_with_cat, -> (latitude, longitude){
joins(:services, :affiliates, :affiliate_plans)
.where("ST_Distance(service.lonlat, 'POINT(:lo :la)') < (affiliate_plan.radius_miles * 1609.34)", lo: longitude, la: latitude)
}
我已经尝试过service.lonlat
的单数和复数。我总是得到一个空虚的关系。我试过在没有使用里程设置值的联接表的情况下获得服务,因此似乎地理空间方面正在起作用。
这是我如何使它起作用:
scope :within_with_cat, -> (latitude, longitude){ joins(affiliate: [ :affiliate_plan]).where(['(ST_Distance(lonlat, \'POINT(%f %f)\') < (affiliate_plans.radius_miles * 1609.34))', longitude, latitude])}
我发现如果我叫Service.within_with_cat(lat, lon).any?
,我将收到调试所需的错误消息。当我打电话给Service.within_with_cat(lat, lon)
时,我只会收到没有错误的关系。