Skip to content

Commit 395ea07

Browse files
committed
Merge PR rails#43322
2 parents 100ad43 + 8565463 commit 395ea07

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

activerecord/CHANGELOG.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,19 @@
1+
* Fix `ActiveRecord::QueryMethods#in_order_of` behavior for integer enums.
2+
3+
`ActiveRecord::QueryMethods#in_order_of` didn't work as expected for enums stored as integers in the database when passing an array of strings or symbols as the order argument. This unexpected behavior occurred because the string or symbol values were not casted to match the integers in the database.
4+
5+
The following example now works as expected:
6+
7+
```ruby
8+
class Book < ApplicationRecord
9+
enum status: [:proposed, :written, :published]
10+
end
11+
12+
Book.in_order_of(:status, %w[written published proposed])
13+
```
14+
15+
*Alexandre Ruban*
16+
117
* Ignore persisted in-memory records when merging target lists.
218

319
*Kevin Sjöberg*

activerecord/lib/active_record/relation/query_methods.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,7 @@ def in_order_of(column, values)
432432
references = column_references([column])
433433
self.references_values |= references unless references.empty?
434434

435+
values = values.map { |value| type_caster.type_cast_for_database(column, value) }
435436
column = order_column(column.to_s) if column.is_a?(Symbol)
436437

437438
spawn.order!(connection.field_ordered_value(column, values))

activerecord/test/cases/relation/field_ordered_values_test.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
require "cases/helper"
44
require "models/post"
5+
require "models/book"
56

67
class FieldOrderedValuesTest < ActiveRecord::TestCase
78
fixtures :posts
@@ -13,6 +14,30 @@ def test_in_order_of
1314
assert_equal(order, posts.map(&:id))
1415
end
1516

17+
def test_in_order_of_with_enums_values
18+
Book.destroy_all
19+
Book.create!(status: :proposed)
20+
Book.create!(status: :written)
21+
Book.create!(status: :published)
22+
23+
order = %w[written published proposed]
24+
books = Book.in_order_of(:status, order)
25+
26+
assert_equal(order, books.map(&:status))
27+
end
28+
29+
def test_in_order_of_with_enums_keys
30+
Book.destroy_all
31+
Book.create!(status: :proposed)
32+
Book.create!(status: :written)
33+
Book.create!(status: :published)
34+
35+
order = [Book.statuses[:written], Book.statuses[:published], Book.statuses[:proposed]]
36+
books = Book.in_order_of(:status, order)
37+
38+
assert_equal(order, books.map { |book| Book.statuses[book.status] })
39+
end
40+
1641
def test_in_order_of_expression
1742
order = [3, 4, 1]
1843
posts = Post.in_order_of(Arel.sql("id * 2"), order.map { |id| id * 2 }).limit(3)

0 commit comments

Comments
 (0)