Forum: Ruby on Rails [PLUGIN] count_from_query - easily convert finder queries in

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Pat M. (Guest)
on 2007-04-04 09:20
(Received via mailing list)
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
Gustav P. (Guest)
on 2007-04-04 11:21
(Received via mailing list)
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.
This topic is locked and can not be replied to.