Size of active record collection
Know the size method to use for activerecord lists
Getting the size on an activerecord collection can trigger a query or load the objects in memory depending on the method you use. There are 3 different methods:
- count - Uses sql
count
query for getting the size from db - length - Loads the elements of the collection into memory to get the size
- size - Hybrid that gets a count from memory if collection is loaded or
count
if not
In most cases (depending on the application), the preferred method is going to be count for getting counter caches or counts on a set of records in a database.
For nice write up on this, take a look at hasmanythrough’s post “count vs length vs size”.