Read more

count vs. size vs. length on ActiveRecord associations

Deleted user #6
March 13, 2013Software engineer

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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot
Posted to makandra dev (2013-03-13 10:38)