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

后端 未结 7 1817
粉色の甜心
粉色の甜心 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 06:20

    If you are using MySQL, you can use FIELD to order results:

    class User < ActiveRecord::Base
      def self.find_in_order(ids)
        self.where(id: ids).order("FIELD(id, #{ids.join(',')})")
      end
    end
    
    User.find_in_order([1, 100, 5, 30, 4, 2, 88, 44])
    
    0 讨论(0)
提交回复
热议问题