views:

530

answers:

3

I have a record set that includes a date field, and want to determine how many unique dates are represented in the record set.

Something like:

Record.find(:all).date.unique.count

but of course, that doesn't seem to work.

+12  A: 

What you're going for is the following SQL:

SELECT COUNT(DISTINCT date) FROM records

ActiveRecord has this built in:

Record.count('date', :distinct => true)
nex3
A: 

Outside of SQL:

Record.find(:all).group_by(&:date).count

ActiveSupport's Enumerable#group_by is indispensable.

m104
+1  A: 

Also, make sure you have an index on the field in your db, or else that query will quickly become sloooow.

(It's much better to do this in SQL, otherwise you pull the entire db table into memory just to answer the count.)

0124816