gitastic gitastic - 5 months ago 6
Ruby Question

How to sort by date, then shuffle within date

I have an array full of events with a date field. I wanted to sort the array by the date field, but then after this is sorted, shuffle the events within each day (but still maintaining the date order):

@events = Event.order('date desc').shuffle....?

This is an example of what I want:


Event 1 (Jan. 2),
Event 2 (Jan. 1),
Event 3 (Jan. 3),
Event 4 (Jan. 1),
Event 5 (Jan. 3)]

I want this order:

Event 2, Event 4, Event 1, Event 3, Event 5

But, on a refresh:

Event 4, Event 2, Event 1, Event 5, Event 3

or, a similar variation, maintain the date order, but shuffle within each day.


Try this:

@events ="").order("date, random()")

This will provide random ordering of the events for the same date.