[PLUGIN] count_from_query - easily convert finder queries into count queries

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

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

and get the same result.

ruby script/plugin install svn://evang.eli.st/public/plugins/count_from_query

Released under the MIT License

Pat Maddox wrote:

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

>

Congrats! This is fantastic!

Gustav Paul