【问题标题】:How to write a :within scope for a polymorphic relationship?如何为多态关系编写 :within 范围?
【发布时间】:2019-01-30 02:30:35
【问题描述】:

我有一个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

如何从PlaceOfInterest 获取存在于Location 上的lonlat 来写入:within 范围?

【问题讨论】:

  • 您尝试过使用联接吗?
  • Property 是什么?你命名了LocationPlaceOfInterest 与他们有什么关系?
  • 我的意思是说 PlaceOfInterest。更新 - 我的坏

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 2016-08-23
    相关资源
    最近更新 更多