【问题标题】:Rails inner join combined with geocoding gemRails 内连接与地理编码 gem 相结合
【发布时间】:2012-09-06 11:14:05
【问题描述】:

我有 2 个相关的导轨模型

class Location < ActiveRecord::Base
  has_many :rates
  geocoded_by ....
end

class Rate < ActiveRecord::Base
 belongs_to :location
end

我正在使用地理编码器 gem - http://www.rubygeocoder.com

我想查找与用户在一定距离内具有特定pair 属性的所有费率。

在 SQL 中,我会对费率进行内部联接

SELECT * FROM rates INNER JOIN locations ON rates.location_id=locations.id;

然后,插入一个 where 条件来过滤 pair 属性,然后在结果表上使用 Geocoder 的 near 方法(near 方法通过将 where 条件插入到使用 latitude 和 longitude 属性计算距离的查询中来工作location) 只选择正确距离内的行

如何在 Rails 中执行此操作?我试过了

rates = Rate.joins(:locations)

我明白了

ActiveRecord::ConfigurationError: Association named 'locations' was not found; perhaps you misspelled it?

我想这样做

rates = Rate.joins(:locations).near(my_latitude, my_longitude, distance).where(:rates => {:pair => 'xxxx'})

但我明白了

undefined method `near' for #<ActiveRecord::Relation:0xa075ff8>

【问题讨论】:

  • 既然是belongs_to,我认为:locations 需要是单数。不确定这是否可行,但您可能只需要重新排序您的方法调用。取决于 gem 如何与 ARel 一起使用。 Rate.near(my_latitude, my_longitude, distance).join(:location).where(:rates =&gt; {:pair =&gt; 'xxxx'})

标签: ruby-on-rails geocoding


【解决方案1】:
near = Location.near(location, radius)
Rate.includes(:location).references(:location).merge(near)

这可以与其他位置或速率范围链接

【讨论】:

    【解决方案2】:

    我知道这是一个旧的,但仍然没有回答,无处:)

    我遇到了同样的问题,然后偶然发现了一个小信息deep down in the geocoder documentation,它说为了使外连接工作(在 rails 中使用包含完成),您应该结合使用 join : select 并为我完成了它(我需要从某个位置的用户那里找到所有产品)。

    所以从我的脑海中,这可能适用于你的情况:

    rates = Location.near(my_latitude, my_longitude, distance, :select => "rates.*").joins(:locations).where(:rates => {:pair => 'xxxx'})
    

    我希望这会有所帮助。

    【讨论】:

    • 这个解决方案产生了很多问题:你不能使用范围,部分不起作用,因为 Rails 试图渲染位置而不是速率,等等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多