Randy Girard

ActiveRecord counting with associations

The other day I had to display the number of children items an object had so I decided to do the following:

# Controller
@customers = Customer.find(:all, :include=>[:receive_payments])

#View
<%= customer.receive_payments.count %>

While this worked for what I needed, it executed the following sql every iteration:

SELECT count(*) AS count_all FROM "receive_payments" WHERE ("receive_payments".customer_ref_list_id = E'850000-1071531366')

I thought this wasn’t right considering I used an association, however when you use count, it forces the use of count(*) on the database. This is where size comes in!!!!

<%= customer.receive_payments.size %>

Now we get the same results without the extra database counts!