Read more

count vs. size vs. length on ActiveRecord associations

Martin Straub
March 13, 2013Software engineer at makandra GmbH

TLDR

  • When counting records in an association, you should use #size in most cases.
  • It will not work if the parent record has never been saved. Also there are finer distinctions between #size and #count. See below.

count

  • Always makes a COUNT(*) query if a counter cache is not set up.
  • If a counter cache is set up on the association, #count will return that cached value instead of executing a new query.

size, if the association has already been loaded

  • Counts elements in the already loaded array.
  • Does not make another query.

size, if the association has not yet been loaded

  • Makes a COUNT(*) query, just like #count

length

  • Always loads the contents of the association into memory, then returns the number of elements loaded.

Caveat for unsaved records

  • If you trigger a COUNT(*) by whatever means, Rails will try to load all children where the foreign key IS NULL. This is not what you want, ever.
  • If you want to count children and not fall into this trap, use association.to_a.size.
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot
Posted by Martin Straub to makandra dev (2013-03-13 10:38)