Reputation: 41964
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!!
Upvotes: 1
Views: 254
Reputation: 64373
You can optimize your first two statements to use the DB sorting, as the rails group functions return OrderedHash
# you can order the result set by the select col position instead of name
avg_scores = Review.average(:score, :group => :aidmodel_id, :order => "2 ASC")
# assuming you don't have 100s of rows here..
rh = Review.where(:aidmodel_id=> @avg_scores.keys).group_by(&:aidmodel_id)
avg_score_set = avg_scores.map {|id, score| [id, score, rh[id]]}
Now avg_score_set is a ordered array of arrays. The inner array has the avg score and reviews.
Upvotes: 1
Reputation: 659187
I wouldn't know about Ruby, but in PostgreSQL you can get array elements in the requested order like this:
SELECT arr[i] AS arr_element
FROM (SELECT '{1,2,3,4,5}'::int[] AS arr, unnest(ARRAY[5, 3, 1, 4]) AS i) x
Upvotes: 1