Sha256: 9eef74412743d861486baade8f3d72cd10460a00405fb99564793c85a6de5807

Contents?: true

Size: 610 Bytes

Versions: 1

Compression:

Stored size: 610 Bytes

Contents

require "active_record/order_by_ids/version"
require "active_record"

module ActiveRecord
  module OrderByIds
    def order_by_ids ids
      order_by(primary_key => ids)
    end

    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
  end
end

ActiveRecord::Base.extend ActiveRecord::OrderByIds

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_record-order_by_ids-0.3.0 lib/active_record/order_by_ids.rb