Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of records that have a unique value in a particular field in ROR?

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.

like image 498
Brent Avatar asked Aug 31 '08 03:08

Brent


2 Answers

This has changed slightly in rails 4 and above :distinct => true is now deprecated. Use:

Record.distinct.count('date')

Or if you want the date and the number:

Record.group(:date).distinct.count(:date)
like image 147
Yule Avatar answered Nov 01 '22 01:11

Yule


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)
like image 85
Natalie Weizenbaum Avatar answered Nov 01 '22 02:11

Natalie Weizenbaum