# How do you rewrite this with the :group option?

**URL:** <https://www.ruby-forum.com/t/how-do-you-rewrite-this-with-the-group-option/146902>\
**Category:** Rails\
**Created:** [August 26, 2008, 5:05pm UTC](https://www.ruby-forum.com/t/how-do-you-rewrite-this-with-the-group-option/146902 "2008-08-26T17:05:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![david](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/aeb1de/32.png) [@david](https://www.ruby-forum.com/u/david)\
**Post date:** [August 26, 2008, 5:05pm UTC](https://www.ruby-forum.com/t/how-do-you-rewrite-this-with-the-group-option/146902/1 "2008-08-26T17:05:58Z")

</div>

Hello,

I would like to rewrite this find\_by\_sql query in terms  
of :group, :limit, etc. options. I don’t know how to handle the  
count(\*) as count part though. Does anybody know how to make a more  
Ruby-like implementation of the following function?

class Tag \< ActiveRecord::Base  
def self.find\_top\_tags(options = {})  
options[:order] ||= ‘count desc, name asc’  
options[:limit] ||= 100  
query = “select tags.id, name, count(\*) as count”  
query \<\< " from taggings, tags"  
query \<\< " where tags.id = tag\_id"  
query \<\< " and context = ‘#{options[:on]}’" if options[:on] != nil  
query \<\< " group by tag\_id"  
query \<\< " order by #{options[:order]}" if options[:order] != nil  
query \<\< " limit #{options[:limit]}" if options[:limit] != nil  
tags = Tag.find\_by\_sql(query)  
end  
end

P.S. I am using acts\_as\_taggable\_on, and finding that this function  
would be nice to have.

---

<div class="post-metadata">

**Author:** ![david](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/aeb1de/32.png) [@david](https://www.ruby-forum.com/u/david)\
**Post date:** [August 26, 2008, 11:49pm UTC](https://www.ruby-forum.com/t/how-do-you-rewrite-this-with-the-group-option/146902/2 "2008-08-26T23:49:50Z")

</div>

Do you mean you don’t want to use find\_by\_sql?

First off, in terms of valid SQL statements, if you want to use count  
(or any other grouping function), you have to group by all the non-  
grouped fields in your select statement. So you would need to have  
“group by tags.id, name”. Use a sql console and try out your  
statements until you get what you want.

you could do something like

find(:join=\>:taggings,  
:select=\>'select tags.id, tags.name, count(taggings.id) as  
tag\_count ‘,  
:limit=\>options[:limit] || 100,  
:order=\>options[:order] || ’ count(taggins.id) desc’)

maybe add :having=\>count(tagging.id) \> 1 or whatever.

It might be easier to use named scopes for adding the conditions.
