Rails内部连接与地理编码宝石相结合

时间:2012-09-06 11:14:06

标签: ruby-on-rails geocoding

我有2个相关的导轨型号

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

class Rate < ActiveRecord::Base
 belongs_to :location
end

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

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

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

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

然后,插入where条件以对pair属性进行过滤,然后在结果表上使用Geocoder的near方法(near方法的工作原理是将where条件插入到查询中,该查询使用纬度和经度属性计算距离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>

2 个答案:

答案 0 :(得分:8)

near = Location.near(location, radius)
Rate.includes(:location).references(:location).merge(near)

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

答案 1 :(得分:2)

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

我遇到了同样的问题,然后偶然发现了一个小信息deep down in the geocoder documentation,其中说为了使外连接工作(在rails中完成包含),你应该使用join in combination with:select and that that it it for me(我需要在特定位置找到用户的所有产品)。

所以,从我的头脑中,这可能适合你的情况:

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

我希望这会有所帮助。

相关问题