gitastic gitastic - 6 months ago 25
Ruby Question

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....?


Example this is what I want:

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

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 similar variation, maintain date order, but shuffle within each day)

Hope someone can help! Thanks!

Answer

Try this:

@events = Event.group("events.id").order("date, random()")

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