考虑一下:
ids = [14195, 6053, 53119, 7513, 5161, 43252, 7633, 627, 54644, 1438]
Foo.find(ids).map(&:id)
返回:
[627, 1438, 5161, 6053, 7513, 7633, 14195, 43252, 53119, 54644]
我能以find
的方式按照相同的顺序返回结果吗?即:
[14195, 6053, 53119, 7513, 5161, 43252, 7633, 627, 54644, 1438]
答案 0 :(得分:3)
参考this
Foo.where(:id => ids).order("field(id, 627, 1438, 5161, 6053, 7513, 7633, 14195, 43252, 53119, 54644").map(&:id)
或where
Foo.where(:id => ids).order("field(id, #{ids.join(',')})").map(&:id)
或find
Foo.find(ids, :order =>"field(id, #{ids.join(',')})").map(&:id)