I have the array [5, 3, 1, 4] which corresponds to the hash keys produced by the following code:
@ordered_hash = Review.group('aidmodel_id').average('score')
@ordered_hash = ActiveSupport::OrderedHash[@ordered_hash.sort_by {|key, value| value }]
@keys = @ordered_hash.keys
Using the keys obtained @keys = [5, 3, 1, 4] I would like to pull some records from my database using:
@reviews = Review.where(:aidmodel_id=>@keys).uniq_by {|x| x.aidmodel_id}
This works well. However, the returned models are in the order that they appear in the database, rather than in the order specified by the keys. This means that the output is sorted randomly, rather than in order of average score.
There must be some way to re-order the multidimensional array returned by Review.where based on the @keys array.. or some way to pull the records out in the correct order.. perhaps using a loop around the SQL query?
Thanks for your help!!