【问题标题】:Search Object by Related object SQL ActiveRecord按相关对象 SQL ActiveRecord 搜索对象
【发布时间】:2012-06-28 17:15:45
【问题描述】:

我有一个带有位置的模型,它本身有一个纬度和经度。我想要的是纬度/经度在某个区域内的交易,所以我尝试了这个:

boundary = self.user.boundary
max_lat, max_lng = boundary.max_coords.latitude, boundary.max_coords.lng
min_lat, min_lng = boundary.min_coords.latitude, boundary.min_coords.lng
lat, long = self.user.location.latitude, self.user.location.longitude
self.all_deals =  Deal.where('location.latitude <= ? AND location.latitude >= ? AND location.longitude <= ? AND location.longitude >= ?', max_lat, min_lat, max_lng, min_lng).limit(10)

SQL 引发异常,指出没有列“location.latitude”。我怎样才能编写相同的东西,但使用 ActiveRecord(首选)或原始 SQL?

【问题讨论】:

    标签: sql ruby-on-rails activerecord where


    【解决方案1】:

    您缺少此查询的联接。

    为了能够使用location,您必须重写查询:

    self.all_deals =  Deal.joins(:location).where('location.latitude <= ? AND location.latitude >= ? AND location.longitude <= ? AND location.longitude >= ?', max_lat, min_lat, max_lng, min_lng).limit(10)
    

    如果您查看生成的 SQL,它现在应该包含对 deal.location_id 的连接。 (我假设位置是通过belongs_tohas_one 关系连接到您的交易的引用模型?)

    查看更多关于加入的信息in the docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-16
      • 2013-03-09
      • 1970-01-01
      • 2013-04-02
      • 2023-04-01
      • 1970-01-01
      • 2021-10-08
      相关资源
      最近更新 更多