Rails inner join combined with geocoding gem

∥☆過路亽.° 提交于 2019-12-21 04:53:08

问题


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>

回答1:


near = Location.near(location, radius)
Rate.includes(:location).references(:location).merge(near)

This is chainable with other Location or Rate scopes




回答2:


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.



来源:https://stackoverflow.com/questions/12298836/rails-inner-join-combined-with-geocoding-gem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!