具有多个联接和参数的滚动范围

问题描述 投票:0回答:1

我已经尝试过其他问题的解决方案,但仍然遇到麻烦。我似乎也找不到是否有调试查询的好方法,因此我只能使用反复试验。

我正在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

我的Affiliatebelongs_to之间具有AffiliatePlan关系:

class Affiliate < ApplicationRecord
    belongs_to :affiliate_plan
end 

我的AffiliatePlanradius_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的单数和复数。我总是得到一个空虚的关系。我试过在没有使用里程设置值的联接表的情况下获得服务,因此似乎地理空间方面正在起作用。

ruby-on-rails join scope ruby-on-rails-5
1个回答
0
投票

这是我如何使它起作用:

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)时,我只会收到没有错误的关系。

© www.soinside.com 2019 - 2024. All rights reserved.