Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix QueryMethods#in_order_of to handle empty order list #43916

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,14 @@
* Fix `QueryMethods#in_order_of` to handle empty order list.

```ruby
Post.in_order_of(:id, []).to_a
```

Also more explicitly set the column as secondary order, so that any other
value is still ordered.

*Jean Boussier*

* Fix quoting of column aliases generated by calculation methods.

Since the alias is derived from the table name, we can't assume the result
Expand Down
10 changes: 7 additions & 3 deletions activerecord/lib/active_record/relation/query_methods.rb
Expand Up @@ -432,10 +432,14 @@ def in_order_of(column, values)
references = column_references([column])
self.references_values |= references unless references.empty?

values = values.map { |value| type_caster.type_cast_for_database(column, value) }
column = order_column(column.to_s) if column.is_a?(Symbol)
if values.empty?
spawn.order!(column)
else
values = values.map { |value| type_caster.type_cast_for_database(column, value) }

spawn.order!(connection.field_ordered_value(column, values))
arel_column = column.is_a?(Symbol) ? order_column(column.to_s) : column
spawn.order!(connection.field_ordered_value(arel_column, values), column)
end
end

# Replaces any existing order defined on the relation with the specified order.
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/relation/field_ordered_values_test.rb
Expand Up @@ -14,6 +14,18 @@ def test_in_order_of
assert_equal(order, posts.map(&:id))
end

def test_unspecified_order
order = [3, 4, 1]
post_ids = Post.in_order_of(:id, order).map(&:id)
expected_order = order + (post_ids - order).sort
assert_equal(expected_order, post_ids)
end

def test_in_order_of_empty
posts = Post.in_order_of(:id, [])
assert_equal(posts.map(&:id).sort, posts.map(&:id))
end

def test_in_order_of_with_enums_values
Book.destroy_all
Book.create!(status: :proposed)
Expand Down