Topic: counting rows.

having a little issue with counting DB rows.

okay I'm trying to figure this out. its a little tagging thing I'm playing with.

db looks a little like this

id    tag
1     hello
2     hello
3     bye bye
4     hello
5     bye bye
6     what?

I want to be able to dynamically count the hello's etc.

I know I can do it via

count.find(:all, :conditions => "tag = 'hello'")

but that only works if I know whats in the DB, is there a rails way of dynamically counting all of these rows?

--

Re: counting rows.

Sure, try this:

Tag.count :group => 'tag'

You'll get something like this:
[["Hello", 4], ["bye bye", 2], ['some other tag', 43]]

Re: counting rows.

Is that a nested array or a hash? I supose I can then sort it with a.sort {}

--

Re: counting rows.

Yeah, it's a nested array and you can sort it like this:

tag_count = Tag.count :group => 'tag' 
totals = {}
tag_count.each {|t| totals[t[0]] = t[1] }
# totals now equals:
# {'hello' => 4, 'bye bye' => 2,'some other tag' => 43}
sorted_tag_count = totals.sort_by {|k,v| v}

Last edited by danger (2006-12-18 18:35:53)

Re: counting rows.

I've just realized I've put this in the wrong forum, hohum.

this seems to be working. but I've needed to add two fields in to the group tag, and while the results are fine. I cant seem to pass the value of the second field into the array/hash. Is this just a limmitation of that result of the .count method?

--