Skip to content

Instantly share code, notes, and snippets.

@aseroff
Created August 11, 2017 15:16
Show Gist options
  • Save aseroff/36c3c0842d204fd0ea736207d19269b4 to your computer and use it in GitHub Desktop.
Save aseroff/36c3c0842d204fd0ea736207d19269b4 to your computer and use it in GitHub Desktop.
Rails scope for maintaining order
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