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 many many times.
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] }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With