Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a Rails record count without quering a 2nd time

I've got a Rails ActiveRecord query that find all the records where the name is some token.

records = Market.where("lower(name) = ?", name.downcase );
rec = records.first;
count = records.count;

The server shows that the calls for .first and .count were BOTH hitting the database.

←[1m←[35mCACHE (0.0ms)←[0m  SELECT "markets".* FROM "markets" WHERE (lower(nam
e) = 'my market') LIMIT 1

←[1m←[36mCACHE (0.0ms)←[0m  ←[1mSELECT COUNT(*) FROM "markets" WHERE (lower(na
me) = 'my market')←[0m

Why is it going to the database to get the count when it can use the results already queried?

I'm concerned about future performance. Today there are 1000 records. When that table holds 8 million rows, doing two queries one for data, and one for count, it will be expensive.

How do I get the count from the collection, not the database?

like image 480
baash05 Avatar asked Jun 01 '12 03:06

baash05


1 Answers

RactiveRecord use lazy query to fetch data from database. If you want to simple count the records, you can only call size of the retrun array.

records = Market.where("lower(name) = ?", name.downcase ).all
records.size
like image 146
Hooopo Avatar answered Nov 04 '22 18:11

Hooopo