Rails内部联接与地理编码gem结合 [英] Rails inner join combined with geocoding gem

查看:42
本文介绍了Rails内部联接与地理编码gem结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个相关的rails模型

I have 2 related rails models

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

class Rate < ActiveRecord::Base
 belongs_to :location
end

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

I am using the geocoder gem - http://www.rubygeocoder.com

我想找到所有具有特定pair属性且与用户相距一定距离的费率.

I want to find all rates with a particular pair attribute that are within a certain distance to the user.

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

In SQL, I would do an inner join on the rates

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

然后,插入一个where条件以对pair属性进行过滤,然后在结果表上使用Geocoder的near方法(Near方法通过在查询中插入一个where条件来工作,该条件使用纬度和经度属性来计算距离位置)以仅选择正确距离内的行

Then, insert a where condition to filter on the pair attribute, and then use the Geocoder's near method on the resulting table (the near method works by inserting a where condition into the query which calculates the distance using latitude and longitude attributes on location) to only select the rows within the right distance

如何在Rails中做到这一点?我尝试过

How can I do this in rails? I tried

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>

推荐答案

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

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

This is chainable with other Location or Rate scopes

这篇关于Rails内部联接与地理编码gem结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆