diff --git a/README.md b/README.md index 5f62af7..ce0b0b1 100644 --- a/README.md +++ b/README.md @@ -9,12 +9,14 @@ Find records in the same order of input array. +Forked from [khiav223577/find_with_order](https://github.com/khiav223577/find_with_order) + ## Installation Add this line to your application's Gemfile: ```ruby -gem 'find_with_order' +gem 'find_with_order', git: 'git://github.com/KRaikk/find_with_order.git' ``` And then execute: diff --git a/lib/find_with_order/mysql_support.rb b/lib/find_with_order/mysql_support.rb index d8dea04..da3ad71 100644 --- a/lib/find_with_order/mysql_support.rb +++ b/lib/find_with_order/mysql_support.rb @@ -2,7 +2,7 @@ module FindWithOrder::MysqlSupport class << self def find_with_order(relation, ids) relation.where(id: ids) - .order("field(#{relation.table_name}.id, #{ids.join(',')})") + .reorder("field(#{relation.table_name}.id, #{ids.join(',')})") .to_a end @@ -16,8 +16,8 @@ def with_order(relation, column, ids, null_first: false) 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") + return relation.reorder("field(#{column}, #{ids.map(&:inspect).join(',')})") if null_first + return relation.reorder("field(#{column}, #{ids.reverse.map(&:inspect).join(',')}) DESC") end end end diff --git a/lib/find_with_order/pg_support.rb b/lib/find_with_order/pg_support.rb index f68a0d5..50c3383 100644 --- a/lib/find_with_order/pg_support.rb +++ b/lib/find_with_order/pg_support.rb @@ -4,7 +4,7 @@ def find_with_order(relation, ids) # return relation.where(id: ids).order("array_position(ARRAY[#{ids.join(',')}], #{relation.table_name}.id)").to_a #array_position is only support in PG >= 9.5 return relation.where(id: ids) .joins("JOIN (SELECT id.val, row_number() over() FROM (VALUES(#{ids.join('),(')})) AS id(val)) AS id ON (#{relation.table_name}.id = id.val)") - .order('row_number') + .reorder('row_number') end def where_with_order(relation, column, ids) @@ -18,6 +18,7 @@ def with_order(relation, column, ids, null_first: false) column = column.to_s end ids = ids.reverse if null_first + ids.reject!(&:blank?) case ids.first when Numeric values = ids.join('),(') @@ -29,8 +30,7 @@ def with_order(relation, column, ids, null_first: false) else raise "not support type: #{ids.first.class}" end - return relation.joins("LEFT JOIN (SELECT id.val, row_number() over() FROM (VALUES(#{values})) AS id(val)) AS id ON (#{column} = id.val)") - .order(null_first ? 'row_number DESC' : 'row_number') + return relation.joins("LEFT JOIN (SELECT id.val, row_number() over() FROM (VALUES(#{values})) AS id(val)) AS id ON (#{column} = id.val)").reorder(null_first ? 'row_number DESC' : 'row_number') end end end