首页 > 解决方案 > 如何为多态关系编写 :within 范围?

问题描述

我有一个Location模型,其他模型有一个belongs_to :locatable, polymorphic: true

因此,类似 a 的内容PlaceOfInterest可能如下所示:

class PlaceOfInterest < ApplicationRecord
  belongs_to :user
  has_one :location, as: :locatable

  # how to do this part?
  scope :within,
    -> (latitude, longitude, radius_meters = 0) {
      where(%{ST_Distance(lonlat, 'POINT(%f %f)') < %d} % [longitude, latitude, radius_meters]) # approx
    }
end

我怎样才能得到lonlat存在的内容LocationPlaceOfInterest编写:within范围?

标签: ruby-on-railsactiverecordruby-on-rails-5rails-activerecord

解决方案


我不确定我是否完全理解您的模型结构,但您应该能够在 where 之前进行连接。注意joins(:location)和 列名locations.lonlat

class PlaceOfInterest < ApplicationRecord
  belongs_to :user
  has_one :location, as: :locatable

  scope :within,
    -> (latitude, longitude, radius_meters = 0) {
      joins(:location).where(%{ST_Distance(locations.lonlat, 'POINT(%f %f)') < %d} % [longitude, latitude, radius_meters]) # approx
    }
end

推荐阅读