I have 2 related rails models
class Location < ActiveRecord::Base
has_many :rates
geocoded_by ....
end
class Rate < ActiveRecord::Base
belongs_to :location
end
I am using the geocoder gem - http://www.rubygeocoder.com
I want to find all rates with a particular pair
attribute that are within a certain distance to the user.
In SQL, I would do an inner join on the rates
SELECT * FROM rates INNER JOIN locations ON rates.location_id=locations.id;
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
How can I do this in rails? I tried
rates = Rate.joins(:locations)
I get
ActiveRecord::ConfigurationError: Association named 'locations' was not found; perhaps you misspelled it?
I want to do this
rates = Rate.joins(:locations).near(my_latitude, my_longitude, distance).where(:rates => {:pair => 'xxxx'})
but I get
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
I know this is an old one, but still not answered, nowhere :)
I ran into the same Problem, then stumbled upon a little info deep down in the geocoder documentation, where it said that in order to make an outer join work (which in rails is done with includes), you should use join in combination with :select and that did it for me (I needed to find all the products from users within a certain location).
So just from the top of my head, this might work in your case:
rates = Location.near(my_latitude, my_longitude, distance, :select => "rates.*").joins(:locations).where(:rates => {:pair => 'xxxx'})
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With