mercredi 15 avril 2015

Sort database query by column and then randomly

Let's say you have a model for Items with an attribute of Votes. Here might be some sample data:



Item, Votes
-----------
Red 4
Blue 5
Black 5
Green 4
Cyan 5
Yellow 4
Orange 4


I want a scope that first sorts it by Votes:



Item, Votes
-----------
Orange 4
Green 4
Yellow 4
Red 4
Blue 5
Black 5
Cyan 5


And then randomizes it within each vote cohort:



Item, Votes
-----------
Green 4
Red 4
Orange 4
Yellow 4
Black 5
Blue 5
Cyan 5


And then limits it to the first two results.


I've tried this:



scope :options, -> { order('random()').order("votes asc").limit 2 }


and this:



scope :options, -> { order("votes asc").order('random()').limit 2 }


But neither works as expected. The first version seems completely random and the second version is not random at all.





Aucun commentaire:

Enregistrer un commentaire