How do you rewrite this with the :group option?


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, name, count(*) as count”
query << " from taggings, tags"
query << " where = 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)

P.S. I am using acts_as_taggable_on, and finding that this function
would be nice to have.

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, name”. Use a sql console and try out your
statements until you get what you want.

you could do something like

:select=>'select,, count( as
tag_count ‘,
:limit=>options[:limit] || 100,
:order=>options[:order] || ’ count( desc’)

maybe add :having=>count( > 1 or whatever.

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs