Module: FindWithOrder::MysqlSupport

Defined in:
lib/find_with_order/mysql_support.rb

Class Method Summary collapse

Class Method Details

.find_with_order(relation, ids) ⇒ Object



5
6
7
8
9
# File 'lib/find_with_order/mysql_support.rb', line 5

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

.where_with_order(relation, column, ids) ⇒ Object



11
12
13
# File 'lib/find_with_order/mysql_support.rb', line 11

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

.with_order(relation, column, ids, null_first: false) ⇒ Object



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

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