MarkD
MarkD

Reputation: 75

shuffle then sort a db query ruby

I am trying to display a list of articles, sorted by day, but displayed randomly for each day.

This is what I have right now:

@articles = Article.all.shuffle.sort_by{|t| t.date_published}.reverse

I was thinking that the sort would take place on the shuffled array, but it doesn't seem like that is happening. Any help would be greatly appreciated!

I have tried group_by by can't seem to get it to work.

Upvotes: 0

Views: 139

Answers (2)

Benjamin Bouchet
Benjamin Bouchet

Reputation: 13181

A little insight on your code first: all will fetch ALL records from the database and pass it to your ruby code, this is resource and time consuming. Then the shuffle, sort_by and reverse are all executed by ruby. You will quickly hit performance issues as your database grow.

Your solution is to let your database server do that work. DB servers are very optimized for all sorting operations. So if you are for example using MySQL you should use this instead:

@articles = Article.order('`articles`.`date_published` DESC, RAND()')

Which will sort primarily by date_published in reverse order, and secondarily randomly for all articles of the same date

Upvotes: 3

jerhinesmith
jerhinesmith

Reputation: 15502

Hmm, here's a fun hack that should work:

@articles = Article.
  all.
  sort_by{|t| (t.date_published.beginning_of_day.to_i * 1000) + rand(100)}

This works by forcing all the dates to be the beginning of the day (so that everything published on '2015-02-19' for example will have the same to_i value. Then you multiply by 1000 and add a random number between 0 and 100 for the sort (any number less than 1000 would work).

Upvotes: 0

Related Questions