Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Here I retrieve a collection of causes from the database. Along with the information from each cause, I want to send the number of users in each cause. This way works, but if experience has told me anything there is probably a much more efficient method to do this. How can I improve this?

  def index
    @causes = Cause.near([params[:lat], params[:lng]],10)
    @causes.each do |i|
      i['count'] = i.users.count
    respond_to do |format|
      format.json { render json: {:success=> 1, :data_type => 'cause',:results => @causes} }
share|improve this question
up vote 5 down vote accepted

You can perform an inner-join on the users table and then group by the

@causes = Cause
  .near([params[:lat], params[:lng]], 10)
  .select('causes.*, count(users) as count')
share|improve this answer
Thanks for the answer! I'm not trying to be a smart ass, but is this better or just different? Can you explain why? Thanks – Emin Israfil Nov 28 '12 at 16:06
This is more efficient because the number of queries to database is reduced to one. It also places the work onto the database which is optimized for this task through caching and indexing. – peterpan Nov 28 '12 at 16:22
Thanks for getting back to me. It doesn't seem to work. More info posted above :) – Emin Israfil Nov 28 '12 at 18:31
@user15872 What does',count(users) as people').joins(:users).group('').first.people output? – peterpan Nov 29 '12 at 0:44
You say its not in the hash but AR is not returning a hash it is returning a ActiveRecord::Relation. What it is printing to the screen is not necessarily what will be in the json. What does this show?',count(users) as people').joins(:users).group('').as_json – peterpan Nov 29 '12 at 16:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.