The return of unique years from the search

Possible duplicate:
Rails: select unique values ​​from a column

Let's say I have 5,000 records that were created in the last two years (2011 and 2012). How can I iterate over all these records and return an array of only unique years [2011, 2012]?

I create a report in which rows are labeled every year, which writes exit and columns are labeled for months. Then td is filled with amounts for each month of each year.

+4
source share
2 answers

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

Model.uniq.pluck(:year) 

edited by:

for your specific requirement you can do

  Model.pluck(:created_at).map{|x| x.year}.uniq 
+5
source

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

+1
source

Source: https://habr.com/ru/post/1439492/


All Articles