Last active
May 6, 2016 17:49
-
-
Save julianlconnor/b3a1907f4442f8defaba3a9d5217a7f7 to your computer and use it in GitHub Desktop.
postgresql order by field(id)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ensures that your models return with the same ordering as ids | |
# e.g., [1,2,3] yields [<YourModel id=1>, <YourModel id=2>, <YourModel id=3>] | |
# via: https://gist.github.com/cpjolicoeur/3590737, brilliant solution | |
values = ids.each_with_index.map { |id, index| "(#{id}, #{index + 1})" }.join(",") | |
YourModel.unscoped.where(id: ids).joins("join (VALUES #{values}) as x(id, ordering) ON listings.id = x.id").order("x.ordering") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment