Friday, 15 April 2011

Rails, ActiveRecord, query id in array of ints, keep order of passed array -


I'm thinking of the best solution for a problem. Suppose we have a list of the ID of the ActiveRecord model:

  id = [1, 100, 5, 30, 4, 2, 88, 44]  

Then I will create a query that selects all users for instance with an ID from the list, but to keep the order. If I will have a list of users with the order of the order by the response ID, but I want to be in the order

  User.where (id: id)  

Be like the array

Do you think this is the best solution here? Select all users and then to manipulate the list of ActiveRecord objects? Perhaps there is one more clever way to do this.

Thank you!

If you are using MySQL, you can order FIELD to:

  class users & lt; ActiveRecord :: base df self.find_in_order (id) self.where (id: id) .order ("FIELD (id, # {id.join (',')} end-end User.find_in_order ([1, 100, 5, 30, 4, 2, 88, 44])  

No comments:

Post a Comment