Get the last 5 unique dates created_at

I am trying to get the last 5 days that an object has. Currently my code is similar to this

Post.uniq('performed_at').ascending.last(5).group_by{|p| p.performed_at}

but I get 4 dates instead of 5, and I think because there are 2 records of the last 5 that were created on the same day. How can I get the last 5 days when a message has a record?

+4
source share
3 answers

You can do:

Post.select('DISTINCT created_at').order('created_at DESC').limit(5).pluck(:created_at)
+3
source

Assuming you just need the dates themselves, not the unique dates, this would be better:

Post.order('created_at desc').uniq.limit(5).pluck('DATE(created_at)')

This will only return unique calendar dates without any specific dates.

0
source

. , .

Post.select('performed_at').uniq.order('performed_at DESC').limit(5).pluck(:performed_at).reverse

I also added reverse, since I want the array of days to return to me in chronological order. I also had uniq () since select ('DISTINCT perform_at') still returned duplicate dates.

Hope this helps.

0
source

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


All Articles