Created
March 31, 2014 06:53
-
-
Save rusllonrails/9886701 to your computer and use it in GitHub Desktop.
ORDER BY IDS SEQUENCE
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
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