ActiveRecord #count versus #length

Let’s say you have an ActiveRecord model with a has_many association. Ever wonder why you receive different results from #count and #length after you append to that has_many collection? Consider this rough example where Parent and Kid are ActiveRecords and Parent will has_many :kids:

parent = Parent.create!! name: 'Evan'
puts "Current length is #{}"
puts "Current count is #{}"

The output will be:

Current length is 0
Current count is 1

The difference in results appear to be happening because of how length() and count() compute their results. length() is only considering what is loaded into heap memory (“cached”), while count() will actually check what is loaded into the DB.

Here’s a great blog post about the difference between the two methods, as well as size().

Written on March 24, 2016 by evanbrodie