Problem
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
end
respond_to do |format|
format.json { render json: {:success=> 1, :data_type => 'cause',:results => @causes} }
end
end
Solution
You can perform an inner-join on the users table and then group by the causes.id.
@causes = Cause
.near([params[:lat], params[:lng]], 10)
.joins('users')
.group('causes.id')
.select('causes.*, count(users) as count')