# \[PLUGIN\] count\_from\_query - easily convert finder queries in

**URL:** <https://www.ruby-forum.com/t/plugin-count-from-query-easily-convert-finder-queries-in/91060>\
**Category:** Rails\
**Created:** [April 4, 2007, 7:20am UTC](https://www.ruby-forum.com/t/plugin-count-from-query-easily-convert-finder-queries-in/91060 "2007-04-04T07:20:43Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pergesu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/22d042/32.png) [@pergesu](https://www.ruby-forum.com/u/pergesu)\
**Post date:** [April 4, 2007, 7:20am UTC](https://www.ruby-forum.com/t/plugin-count-from-query-easily-convert-finder-queries-in/91060/1 "2007-04-04T07:20:43Z")

</div>

count\_from\_query gives you the ability to generate a COUNT query from  
a standard Rails find.

For example, if you have the query

User.find :all

it would be trivial to get a count:

User.count

however, if you have a more specific finder method, such as

class Company \< ActiveRecord::Base  
def complete\_videos  
Video.find :all, :conditions =\> “company\_id=#{id} AND  
status=‘complete’”, :order =\> “created\_at DESC”  
end  
end

Getting the count isn’t quite as easy. You could just call #size on  
the returned array, but it’s wasteful if you don’t actually need the  
records. You could write a complete\_videos\_count method, but it  
doesn’t feel very DRY to have two methods every time you want to do a  
count query as well.

With count\_from\_query, it’s cake

videos\_count = ActiveRecord::Base.count\_from\_query {  
my\_company.complete\_videos }

You can wrap any AR find call in count\_from\_query to have it be  
converted into a count query.

Association proxies work the same way. We could change the  
complete\_videos definition to be

class Company \< ActiveRecord::Base  
def complete\_videos  
videos.find :all, :conditions =\> “status=‘complete’”, :order =\>  
“created\_at DESC”  
end  
end

and get the same result.

ruby script/plugin install  
svn://evang.eli.st/public/plugins/count\_from\_query

Released under the MIT License

---

<div class="post-metadata">

**Author:** ![pergesu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/22d042/32.png) [@pergesu](https://www.ruby-forum.com/u/pergesu)\
**Post date:** [April 4, 2007, 9:21am UTC](https://www.ruby-forum.com/t/plugin-count-from-query-easily-convert-finder-queries-in/91060/2 "2007-04-04T09:21:54Z")

</div>

Pat M. wrote:

> the returned array, but it’s wasteful if you don’t actually need the  
> converted into a count query.
> 
> and get the same result.
> 
> ruby script/plugin install svn://evang.eli.st/public/plugins/count\_from\_query
> 
> Released under the MIT License
> 
> >

Congrats! This is fantastic!

Gustav P.
