Module: OrderByIds

Defined in:
lib/order_by_ids.rb,
lib/order_by_ids/error.rb,
lib/order_by_ids/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#order_by_ids(ids) ⇒ Object

Order model by array of ids.

Returns

  • ActiveRecord



9
10
11
12
13
14
15
16
17
18
19
# 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