如何以相同的顺序查找返回?

时间:2013-05-31 06:46:33

标签: ruby-on-rails ruby-on-rails-3 activerecord

考虑一下:

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]

1 个答案:

答案 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)