I've tried solutions from other questions but am still having trouble. I also can't seem to find if there is a good way to debug the query, so I've only been able to use trial and error.
I am creating a scope on Service
.
My Service
has an optional belongs_to
relationship with `Affiliate:
class Service < ApplicationRecord
belongs_to :affiliate, optional: true
end
Service
also has a lonlat
column:
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
My Affiliate
has a belongs_to
relationship with AffiliatePlan
:
class Affiliate < ApplicationRecord
belongs_to :affiliate_plan
end
My AffiliatePlan
has a radius_miles
column:
create_table "affiliate_plans", force: :cascade do |t|
t.decimal "radius_miles"
end
Given a longitude and a latitude, my goal is to find all services that are within their AffiliatePlan
's radius from the coordinates.
Here's my latest attempt in my Service
class:
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)
}
I have tried both the singular and plural for service.lonlat
. I always get an empty relation back. I have tried without the join tables using a set value for the miles and have gotten back services, so it seems the geospatial side of things is working.
Here's how I was able to get it working:
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])
}
One of my biggest areas of confusion was that I didn't need to join the table for the model the scope is in.
I discovered that if I called Service.within_with_cat(lat, lon).any?
I would receive the error messages needed for debugging. When I called Service.within_with_cat(lat, lon)
I would only receive a relation with no errors.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.