如何在多态关系的范围内编写:in?

时间:2019-01-30 02:30:35

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

我有一个Get-ADPrincipalGroupMembership someuser | Select-Object -property @{name='Name';e={"$($_.name)_1234"}} 模型,其他模型有Location

因此,类似belongs_to :locatable, polymorphic: true的内容可能看起来像这样:

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上存在的Location来编写PlaceOfInterest范围?

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全了解您的模型结构,但是您应该只能够在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