ruby-on-rails - 如何为多态关系编写 :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
存在的内容Location
来PlaceOfInterest
编写:within
范围?
解决方案
我不确定我是否完全理解您的模型结构,但您应该能够在 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
推荐阅读
- python - 如何让 tkinter 工作(在 vim 中)以及如何让 python-3.x 作为 linux 的默认 python 运行?
- java - Selenium - 将系统日志输出到文本文件
- angular - 同意后如何使用 Angular 加载模块?
- typescript - 使用泛型参数作为文字字段名称创建新类型
- javascript - 为什么不允许此操作
- javascript - 如何向下拉列表添加另一个值
- python - 优化复杂的 Pandas 操作
- python - 通过 JupyterLab bash 访问 Google Cloud
- c# - SSH.Net 上传文件到 SFTP 服务器返回带有“失败”消息的异常,没有明确的详细信息
- reactjs - 条件渲染反应js