module OrderByIds

Constants

VERSION

Public Instance Methods

order_by_ids(ids) click to toggle source

Order model by array of ids.

Returns

  • ActiveRecord

# File lib/order_by_ids.rb, line 9
def order_by_ids(ids)
  return order(:id) if ids.blank?

  order_by = ['CASE']
  ids.each_with_index do |id, index|
    order_by << "WHEN #{name.downcase.pluralize}.id='#{id}' THEN #{index}"
  end

  order_by << 'END'
  order(order_by.join(' '))
end