Sha256: e623ec4aa483bd0d2efe91750081785e7a30d71b04f96860f496ff29fd9f4c39

Contents?: true

Size: 942 Bytes

Versions: 1

Compression:

Stored size: 942 Bytes

Contents

# frozen_string_literal: true

module FindWithOrder::MysqlSupport
  class << self
    def find_with_order(relation, ids)
      relation.where(id: ids)
              .order("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("field(#{column}, #{ids.map(&:inspect).join(',')})") if null_first 
      return relation.order("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.0 lib/find_with_order/mysql_support.rb