ActiveRecord order by external array

后端 未结 3 1558
野的像风
野的像风 2020-12-05 19:55

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         


        
3条回答
  •  春和景丽
    2020-12-05 20:08

    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)}
    

提交回复
热议问题