Module: Hurray::ClassMethods

Defined in:
lib/hurray.rb

Instance Method Summary collapse

Instance Method Details

#ordered_with(ids) ⇒ Object

Get records ordered according to the ids order

Example:

>> User.ordered_with([4,2,6])
=> User::ActiveRecord_Relation
=> [#<User id: 4 ...>, #<User id: 2 ...>, #<User id: 6 ...>]

Arguments:

ids: (Array)


15
16
17
18
19
20
21
22
# File 'lib/hurray.rb', line 15

def ordered_with(ids)
  order_clause = 'CASE id '
  ids.each_with_index do |id, index|
    order_clause << sanitize_sql_array(['WHEN ? THEN ? ', id, index])
  end
  order_clause << sanitize_sql_array(['ELSE ? END', ids.length])
  where(id: ids).order(order_clause)
end