Ad

How Can I Count The Number Of Records That Have A Unique Value In A Particular Field In ROR?

- 1 answer

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.

Ad

Answer

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)
Ad
source: stackoverflow.com
Ad