ActiveRecord count

Posted on


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} }


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')

Leave a Reply

Your email address will not be published. Required fields are marked *