Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post.count to_sql in Rails3?

I have a model name Post. When I try to run Post.count I get a result without a problem. However, I suspect that Ruby is used to count the number of posts returned.

Instead, I'd like to use SQL to count the number of posts, as it is much faster.

The only way I have found to achieve this using Arel is Post.select("COUNT(id)"). Is there no way to run a count command without explicitly calling select on the model? Thanks!

like image 278
Yuval Karmi Avatar asked Jan 02 '11 05:01

Yuval Karmi


2 Answers

Post.count should generate the query:

SELECT COUNT(*) FROM "posts"

Edit: You can see the queries generated by looking at your development.log file.

like image 87
Sean Hill Avatar answered Sep 22 '22 18:09

Sean Hill


Is that what you want? :

Post.where(your_sql).count

Read here

like image 28
Alexey Avatar answered Sep 19 '22 18:09

Alexey