Sha256: 2e4dd01aa65896a01d9ef1d4df2bebb82b357d24d4f25d4a0d4597fe6d459bd0

Contents?: true

Size: 971 Bytes

Versions: 1

Compression:

Stored size: 971 Bytes

Contents

# frozen_string_literal: true

module FindWithOrder::MysqlSupport
  class << self
    def find_with_order(relation, ids)
      relation.where(id: ids)
              .order(Arel.sql("field(#{relation.table_name}.id, #{ids.join(',')})"))
              .to_a
    end

    def where_with_order(relation, column, ids)
      with_order(relation.where(column => ids), column, ids, null_first: true)
    end

    def with_order(relation, column, ids, null_first: false)
      if column.is_a?(Symbol) and relation.column_names.include?(column.to_s)
        column = "#{relation.connection.quote_table_name(relation.table_name)}.#{relation.connection.quote_column_name(column)}"
      else
        column = column.to_s
      end
      return relation.order(Arel.sql("field(#{column}, #{ids.map(&:inspect).join(',')})")) if null_first
      return relation.order(Arel.sql("field(#{column}, #{ids.reverse.map(&:inspect).join(',')}) DESC"))
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
find_with_order-1.3.1 lib/find_with_order/mysql_support.rb