如何使用连接在AR请求中使用范围?

时间:2012-04-13 10:35:22

标签: ruby-on-rails activerecord arel

在我的情况下,我有一个模型Product has_one Location

我使用地理编码器宝石来搜索距离附近的位置。

请求Location.near([0,0],100)如下所示:

  

SELECT位置。*,6371.0 * 2 * ASIN(SQRT(POWER(SIN((0 - locations.latitude)* PI()/ 180/2),2)+ COS(0 * PI()/ 180) * COS(locations.latitude * PI()/ 180)* POWER(SIN((1 - locations.longitude)* PI()/ 180/2),2)))AS距离,CAST(DEGEES(ATAN2)(RADIANS(经度 - 1),RADIANS(纬度 - 0)))+ 360 AS十进制)%360 AS轴承FROM \“locations \”WHERE(6371.0 * 2 * ASIN(SQRT(POWER(SIN((0 - locations.latitude)* PI()/ 180/2),2)+ COS(0 * PI()/ 180)* COS(locations.latitude * PI()/ 180)* POWER(SIN((1 - locations.longitude)* PI( )/ 180/2),2)))< = 20)按距离排序

我想做这样的事情:

Product.where(...).joins(:location).dosomething

我该怎么做?

2 个答案:

答案 0 :(得分:0)

Location#near是一个命名范围?如果是这样,您可以使用Product运算符将其与&范围合并。我认为这应该有效:

class Product
  scope :near, lambda { |coord, dist| joins(:location) & Location.near(coord, dist) }

  ...
end

然后你可以像这样使用它:

Product.near([0, 0], 100)

答案 1 :(得分:0)

另一种可能性,因为合并范围似乎不起作用:

class Product
  scope :near, lambda { |coord, dist| where(:id => Location.near(coord, dist).all.map(&:locationable_id) }

  ...
end

和其他答案的用法一样:

Product.near([0, 0], 100)