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

Solution 1:

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)

Solution 2:

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)

Solution 3:

Outside of SQL:

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

ActiveSupport's Enumerable#group_by is indispensable.