Skip to content

Instantly share code, notes, and snippets.

@rusllonrails
Created March 31, 2014 06:53
Show Gist options
  • Save rusllonrails/9886701 to your computer and use it in GitHub Desktop.
Save rusllonrails/9886701 to your computer and use it in GitHub Desktop.
ORDER BY IDS SEQUENCE
1. Mysql only
> ids = [11,31,29]
=> [11, 31, 29]
> Page.where(id: ids).order("field(id, #{ids.join(',')})")
2. Postrgesql variant
def self.order_by_ids(ids)
order_by = ["case"]
ids.each_with_index.map do |id, index|
order_by << "WHEN id='#{id}' THEN #{index}"
end
order_by << "end"
order(order_by.join(" "))
end
User.where(:id => [3,2,1]).order_by_ids([3,2,1]).map(&:id)
#=> [3,2,1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment