Suppose I have a non-empty array ids of Thing object ids and I want to find the corresponding objects using things = Thing.find_all_by_id(ids). My impression is that things will not necessarily have an ordering analogous to that of ids.
-
Is my impression correct?
-
If so, what can I used instead of
find_all_by_idthat preserves order and doesn’t hit the database unnecessarily many times?
Check it out:
where(:id => ids)will generate a query using anIN(). Then the sort! method will iterate through the query results and compare the positions of the id’s in the ids array.