I've fetched a number of ids through MapReduce. I've sorted those ids by some criteria and now I need to get those objects in this particular order:
MyModel.find(ids)
Right? But it returns objects not in the order ids are stored. Looks like this is just the same as
MyModel.where(:_id.in => ids)
which won't return fetched objects in just the same order as stored ids.
Now I can do this
ids.map{|id| MyModel.find(id)}
which will do the job but it will knock the database man开发者_运维问答y many times.
Was working on a similar problem and found a bit more concise solution:
objs = MyModel.find(ids).sort_by{|m| ids.index(m.id) }
basically just using the sort block to snag the index of the the element.
You can do the ordering by hand after you have all your objects. Something like this:
ordering = { }
ids.each_with_index { |id, i| ordering[id] = i }
objs = MyModel.find(ids).sort_by { |o| ordering[o.id] }
精彩评论