Sort list of objects according to an array (Rails)
问题 I have an array if ids from a table e.g: b = [659, 658, 656, 645, 644, 657, 634, 643, 649, 650, 651, 636, 633, 607, 605, 604, 648, 647, 675, 674, 667, 499] I use it for retrieving a list of objects from tat table: k = Photo.where(id:b) What I get is a list of objects which are NOT sorted in the same order as the array. How can I do that? 回答1: If ids are unique You can use index_by and values_at : k = Photo.where(id: b).index_by(&:id).values_at(*b) Example : b = [5,3,1] Country.where(id: b) #=