Does ActiveRecord find_all_by_X preserve order? If not, what should be used instead?
activerecord, ruby-on-rails
Solution
- Yes
- Use Array#sort
Check it out:
Thing.where(:id => ids).sort! {|a, b| ids.index(a.id) <=> ids.index(b.id)}
`where(:id => ids)` will generate a query using an `IN()`. Then the sort! method will iterate through the query results and compare the positions of the id's in the ids array.
Problem
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_id` that preserves order and doesn't hit the database unnecessarily many times?