2012-04-13 36 views
0

在我的情況中,我有一個模型產品has_one位置如何在加入的AR請求中使用作用域?

我使用geocoder gem搜索距離附近的位置。

請求Location.near([0,0],100)是這樣的:。

SELECT位置*,6371.0 * 2 * ASIN(SQRT(POWER(SIN((0 - 位置((1 - 位置。經度)* PI()/ 180/2),2)+ COS(0 * PI()/ 180)* COS(locations.latitude * PI()/ 180)* POWER )* PI()/ 180/2),2)))作爲距離,CAST(DEGREES(ATAN2(RADIANS(經度-1),RADIANS(緯度-0)))+ 360 AS十進制) (位置\緯度)* PI()/ 180/2),2)+ COS(0 * PI()/ 180)* COS (location.latitude * PI()/ 180)* POWER(SIN((1-locations.longitude)* PI()/ 180/2),2)))< = 20)ORDER BY distance

我想要做這樣的事情:

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

我該怎麼辦呢?

回答

0

Location#near是一個命名範圍?如果是這樣,您可以使用&運算符將它與Product範圍合併。我想,這應該工作:

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

    ... 
end 

然後,你可以使用它像這樣:

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

是,這是一個範圍。我嘗試了它,並有3個查詢:建議加載(5442.1ms)選擇「提案」。*從「提案」INNER JOIN「位置」ON「位置」。「locationable_id」=「提案」。「ID」AND「位置「。」「locationable_type」='建議' 位置負載(186.6ms)選擇位置。*,6371.0 * 2 * ASIN(SQRT(POWER(SIN((0 - locations.latitude)... 建議負載(4920.5ms) SELECT「proposals」。* FROM「proposals」 – 2012-04-13 11:24:59

+0

什麼是提案?您可以顯示「附近位置#」的代碼嗎? – tsherif 2012-04-13 11:27:15

+0

提案==產品。位置#near => https://github.com/alexreisner/geocoder /blob/master/lib/geocoder/stores/active_record.rb#L34 – 2012-04-13 12:36:56

0

另一種可能性,因爲合併範圍似乎不工作:

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

    ... 
end 

和其他答案中的用法一樣:

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

對不起這個解決方案不適合生產 – 2012-04-16 09:10:52

相關問題