Skip to content

Instantly share code, notes, and snippets.

@julianlconnor
Last active May 6, 2016 17:49
Show Gist options
  • Save julianlconnor/b3a1907f4442f8defaba3a9d5217a7f7 to your computer and use it in GitHub Desktop.
Save julianlconnor/b3a1907f4442f8defaba3a9d5217a7f7 to your computer and use it in GitHub Desktop.
postgresql order by field(id)
# 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