2012-06-28 126 views
0

我有一个位置模型,它本身有一个经度和纬度。我要的是其拉/长是在一定区域内交易,所以我想这:搜索对象相关对象SQL ActiveRecord

boundary = self.user.boundary 
max_lat, max_lng = boundary.max_coords.latitude, boundary.max_coords.lng 
min_lat, min_lng = boundary.min_coords.latitude, boundary.min_coords.lng 
lat, long = self.user.location.latitude, self.user.location.longitude 
self.all_deals = Deal.where('location.latitude <= ? AND location.latitude >= ? AND location.longitude <= ? AND location.longitude >= ?', max_lat, min_lat, max_lng, min_lng).limit(10) 

SQL抛出一个异常说有没有列“location.latitude”。我怎么能写同样的东西,但要么使用ActiveRecord(首选)或原始SQL?

回答

0

您错过了此查询中的连接。

为了能够使用location你必须重写查询:

self.all_deals = Deal.joins(:location).where('location.latitude <= ? AND location.latitude >= ? AND location.longitude <= ? AND location.longitude >= ?', max_lat, min_lat, max_lng, min_lng).limit(10) 

如果你看一下生成的SQL现在应该包括参加过deal.location_id。 (我假设位置连接到您的交易throuh一个belongs_tohas_one关系的参考模型?)

查看更多信息上加入in the docs