Picture the following fake Rails code:
@companies = Company.all
[some stuff]
@companies.reject! {|company| company.staff_count < 10}
And assume there are 50 companies in the database, with 10 of them having a staff count less than 10.
What’s the value of @companies.count?
As I found this morning, it’s 50, not 40.
Calling count on an ActiveRecord result set will trigger a new SQL query to get the count, so it has nothing to do with the current state of the object.
@companies.size, on the other hand, will return the correct number.
And yes, I’m aware of the code smell in that example (and the underlying actual code it was based on.) A scope would probably make more sense instead of the reject call, but even then count would be going to the database to check its numbers.
This is an example of where it’s best not to assume anything, but also to check your development logs for the SQL calls your page is generating. There are opportunities for optimization that can come out of that, for sure, but there are also times when you’ll get a hint that your code is doing something you didn’t quite expect it to.
Does anyone know of a good Rails logfile analyzer?

