4

Possible Duplicate:
Rails: select unique values from a column

Lets say I have 5000 records that were created in the last two years (2011 & 2012). How can I loop through all those records and return an array of only the unique years [2011, 2012]?

I'm creating a report where rows are labeled by each year that records exit and columns are labeled by months. Then td is populated by sum totals for each month of each year.

Community
  • 1
  • 1
hellion
  • 4,602
  • 6
  • 38
  • 77

2 Answers2

5

see Rails: select unique values from a column for a more rails approach..

Model.uniq.pluck(:year)

edited:

for your specific requirment you can do

 Model.pluck(:created_at).map{|x| x.year}.uniq
Community
  • 1
  • 1
Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244
1

Model.select("created_at").map{ |i| i.created_at.year }.uniq is working. Im still digging around for a cleaner way to do it.

hellion
  • 4,602
  • 6
  • 38
  • 77
  • Went with this solution inspired by RailsN00b. Model.uniq.pluck("EXTRACT(YEAR FROM whatever_date)") – hellion Oct 12 '12 at 23:34