I have model with a location, which itself has a latitude and longitude. What I want is the Deal whose lat/long are within a certain region, so I tried this:
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 raises an exception saying there isn’t a column ‘location.latitude’. How can I write the same thing but either using ActiveRecord (preferred) or in raw SQL?
You are missing the joins on this query.
To be able to use
locationyou have to rewrite the query:If you look at the generated SQL it now should include a join over the
deal.location_id.(I am assuming location is a referenced model that is connected to your deal throuh a
belongs_toorhas_onerelation?)See more info on joins in the docs