Group by Distance in Rails/SQL?
Is it possible to group by distance using the geokit-rails
gem for ActiveRecord?
Say I have 10,000 users and I want to know how many are 1 mile, 2 miles... 100 miles from a point. How can I do that in as few queries as possible?
Doing something like this kills performance obviously:
(1..100).map { |i| User.count(:within => i, :origin => location) }
Is there someway to do:
开发者_JAVA百科User.count(:within => 100, :origin => location, :group => "distance / 100") # some sort of math perhaps
Any point in the right direction would be awesome! Some sort of way to chunk the records in one db call by a range.
I think the following db call will do what you ask for:
result = User.all(:select => "ROUND(distance / 100) AS distance, COUNT(*) AS user_count",
:group => "ROUND(id / 100)")
Since this will not load an actual user instance, you have to specify in the select what data you want to access. Then you can loop through the result like this:
<% result.each do |group| %>
<p>Distance: <%= group.distance %>, Number of users: <%= group.user_count %></p>
<% end %>
精彩评论