I have an array of ids, stored in some external storage (rails cache or redis). In controller\'s action I fetch this data and select object using it, i.e.
id
I just released a gem (order_as_specified) that allows you to do native SQL ordering like this:
MyModel.where(id: ids).order_as_specified(id: ids)
It returns an ActiveRecord relation, and thus can be chained with other methods:
MyModel.where(id: ids).order_as_specified(id: ids).limit(3)
If you're curious, under the hood it's constructing:
... ORDER BY ID='5' DESC, ID='1' DESC, ID='17' DESC, ID='84' DESC
If you don't mind receiving an array instead of an ActiveRecord Collection, you can use:
result = MyModel.find(ids).sort_by {|m| ids.index(m.id)}
If the order of the array is always the same you could add a cached order column to you're database table.
MyModel.order("cached_order")