Read more
count vs. size vs. length 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
.
Opscomplete
powered by
Save money by migrating from AWS to our fully managed hosting in Germany.
-
Trusted by over 100 customers
-
Ready to use with Ruby, Node.js, PHP
-
Proactive management by operations experts
Read more
Show archive.org snapshot
Posted by Martin Straub to makandra dev (2013-03-13 10:38)