Created
August 11, 2017 15:16
-
-
Save aseroff/36c3c0842d204fd0ea736207d19269b4 to your computer and use it in GitHub Desktop.
Rails scope for maintaining order
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
class Something < ActiveRecrd::Base | |
scope :for_ids_with_order, ->(ids) { | |
order = sanitize_sql_array( | |
["position(id::text in ?)", ids.join(',')] | |
) | |
where(:id => ids).order(order) | |
} | |
end | |
# usage: | |
Something.for_ids_with_order([1, 3, 2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment