Posted over 6 years ago. Visible to the public. Repeats. Linked content.

count vs. size on ActiveRecord associations

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.
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Martin Straub
Last edit:
about 4 years ago
by Henning Koch
Keywords:
has_many, scope, relation
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Martin Straub to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more