ActiveRecord order by external array

后端 未结 3 1556
野的像风
野的像风 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:02

    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
    
    0 讨论(0)
  • 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)}
    
    0 讨论(0)
  • 2020-12-05 20:10

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

    0 讨论(0)
提交回复
热议问题