JAR.JAR.beans
JAR.JAR.beans

Reputation: 10004

Force order on a result return from ActiveRecord

I have the following Array (for example):

array = [234,675,11,233,99]

I than Run something like the following ActiveRecord Query:

User.where(id: array)

Array returned will be randomly ordered.

However, I want the returned results to be based on the order of the original array (i.e. id=234 to be first and id=99 to be last).

I could loop on the array and fire 5 separated queries, is there better way to do so?

Upvotes: 0

Views: 95

Answers (1)

JAR.JAR.beans
JAR.JAR.beans

Reputation: 10004

Duplicated with:

ActiveRecord.find(array_of_ids), preserving order

So basically the code should be:

User.find(ids).order("field(id, #{ids.join(',')})")

Upvotes: 2

Related Questions