【发布时间】:2020-09-22 17:18:37
【问题描述】:
我尝试了其他问题的解决方案,但仍然遇到问题。我似乎也找不到调试查询的好方法,所以我只能使用试错法。
我正在Service 上创建一个范围。
我的Service 与`Affiliate 有一个可选的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 与AffiliatePlan 有belongs_to 关系:
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 的单数和复数。我总是得到一个空的关系。我已经尝试过不使用里程设置值的连接表,并且已经恢复了服务,所以看起来地理空间方面的工作正在发挥作用。
【问题讨论】:
-
我会从在 TablePlus(或类似应用程序)之类的东西中使用纯 SQL 开始。一旦你有工作的 SQL 查询,将它转换成 Rails 范围会容易得多。
标签: ruby-on-rails join scope ruby-on-rails-5