Christian Fazzini
Christian Fazzini

Reputation: 19713

How to make find return in the same order?

Consider this:

ids = [14195, 6053, 53119, 7513, 5161, 43252, 7633, 627, 54644, 1438]

Foo.find(ids).map(&:id) returns:

[627, 1438, 5161, 6053, 7513, 7633, 14195, 43252, 53119, 54644]

Any way I can make find return the results in the same order they were put in? i.e.:

[14195, 6053, 53119, 7513, 5161, 43252, 7633, 627, 54644, 1438]

Upvotes: 0

Views: 157

Answers (1)

Salil
Salil

Reputation: 47472

Ref this

Foo.where(:id => ids).order("field(id, 627, 1438, 5161, 6053, 7513, 7633, 14195, 43252, 53119, 54644").map(&:id)

OR with where

Foo.where(:id => ids).order("field(id, #{ids.join(',')})").map(&:id)

OR with find

Foo.find(ids, :order =>"field(id, #{ids.join(',')})").map(&:id)

Upvotes: 3

Related Questions