【发布时间】: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 => {:pair => 'xxxx'})