Skip to content

Commit

Permalink
handle case of nil inside array value for in in_order_of
Browse files Browse the repository at this point in the history
  • Loading branch information
doits committed Oct 4, 2024
1 parent 614c2cd commit 03fe657
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
12 changes: 9 additions & 3 deletions activerecord/lib/active_record/relation/query_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -733,11 +733,13 @@ def in_order_of(column, values, filter: true)
scope = spawn.order!(build_case_for_value_position(arel_column, values, filter: filter))

if filter
values = values.flatten(1)

where_clause =
if values.include?(nil)
arel_column.in(values.compact.flatten(1)).or(arel_column.eq(nil))
arel_column.in(values.compact).or(arel_column.eq(nil))
else
arel_column.in(values.flatten(1))
arel_column.in(values)
end

scope = scope.where!(where_clause)
Expand Down Expand Up @@ -2142,7 +2144,11 @@ def build_case_for_value_position(column, values, filter: true)
node = Arel::Nodes::Case.new
values.each.with_index(1) do |value, order|
if value.is_a?(Array)
node.when(column.in(value)).then(order)
if value.include?(nil)
node.when(column.in(value.compact).or(column.eq(nil))).then(order)
else
node.when(column.in(value)).then(order)
end
else
node.when(column.eq(value)).then(order)
end
Expand Down
13 changes: 13 additions & 0 deletions activerecord/test/cases/relation/field_ordered_values_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,17 @@ def test_in_order_of_with_array_values

assert_equal([3, 2, 5, 4, 7, 1], posts.map(&:id))
end

def test_in_order_of_with_array_values_with_nil
Book.destroy_all
Book.create!(format: "paperback")
Book.create!(format: "ebook")
Book.create!(format: nil)
Book.create!(format: "letter")
Book.create!(format: "digital")

order = ["ebook", ["paperback", nil, "digital"], "letter"]
books = Book.in_order_of(:format, order).order(format: :desc)
assert_equal(["ebook", "paperback", "digital", nil, "letter"], books.map(&:format))
end
end

0 comments on commit 03fe657

Please sign in to comment.