Last Updated: February 25, 2016
·
703
· leomao10

count and size for ActiveRecord

In ActiveRecord, size and count will both call database SQL and return the size for the collection.

However, there is still some subtle difference in Rails 3.2 ( I haven't tried in Rails 4.0)

Say I have a model call User like this:

Class User < ActiveRecord::Base
   has_many :posts
end

And if I create a user like this:

user = User.new
user.posts = [ Post.new ]

Then before user saved, user.posts.count will return 0 and user.posts.size will return 1

And the result will become the same after user.save

2 Responses
Add your response

If you do counting a lot you should cache it with counter_cache http://railscasts.com/episodes/23-counter-cache-column

over 1 year ago ·

@mrfoto That is a valid point, but in my project, the actual model I have the count and size problem is a model call Claim. And I use job_seekers.count to calculate claim amount, and job_seekers.count will only be used once and not called in other places, so it is a bit overkill to create countercachecolumn for job_seekers.count in my case. If I need to call job_seekers.count more than once outside Claim model, I will use counter_cache column for sure

Cheers

over 1 year ago ·