Module: ActiveRecord::OrderByIds

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

Constant Summary collapse

VERSION =
"0.3.0"

Instance Method Summary collapse

Instance Method Details

#order_by(hash) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'lib/active_record/order_by_ids.rb', line 10

def order_by hash
  hash.reduce(reorder(false)) do |scope, (key, ids)|
    ids.map! { |id| connection.quote(id) }
    fragments = []
    fragments += ["#{key} NOT IN (#{ids.join(",")}) OR #{key} IS NULL"] if ids.any?
    fragments += ids.reverse.map { |id| "#{key}=#{id}" }
    scope.order!(Arel.sql(fragments.join(", ")))
  end
end

#order_by_ids(ids) ⇒ Object



6
7
8
# File 'lib/active_record/order_by_ids.rb', line 6

def order_by_ids ids
  order_by(primary_key => ids)
end