Rails, ActiveRecord, query id in array of ints, keep order of passed array

后端 未结 7 1896
粉色の甜心
粉色の甜心 2021-02-01 05:38

I am thinking about the best solution for a problem. Let\'s say that we have a list of ids of ActiveRecord model:

ids = [1, 100, 5, 30, 4, 2, 88, 44]
         


        
7条回答
  •  感情败类
    2021-02-01 05:59

    Another possibility for Postgres (9.4 or later):

    ordered_ids = [1, 100, 5, 30, 4, 2, 88, 44]
    User.joins("join unnest('{#{ordered_ids.join(',')}}'::int[]) WITH " \
               "ORDINALITY t(id, ord) USING (id)").reorder('t.ord')
    

    Notice that the reorder is extremely important.

    Solution based on https://stackoverflow.com/a/35456954

提交回复
热议问题