Skip to content

Commit f008c31

Browse files
authored
Merge pull request rails#52015 from maniSHarma7575/51991-pluck-columns-should-correctly-casts-types-when-using-postgresql
[FIX] Pluck columns should correctly casts types when using postgresql
2 parents f4c39b5 + a35074e commit f008c31

File tree

2 files changed

+12
-17
lines changed

2 files changed

+12
-17
lines changed

activerecord/lib/active_record/relation/calculations.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -604,7 +604,7 @@ def type_cast_pluck_values(result, columns)
604604
model.attribute_types.fetch(name = result.columns[i]) do
605605
join_dependencies ||= build_join_dependencies
606606
lookup_cast_type_from_join_dependencies(name, join_dependencies) ||
607-
result.column_types[name] || Type.default_value
607+
result.column_types[i] || Type.default_value
608608
end
609609
end
610610
end

activerecord/test/cases/calculations_test.rb

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -847,6 +847,10 @@ def test_pluck_type_cast
847847
assert_equal [ topic.approved ], relation.pluck(:approved)
848848
assert_equal [ topic.last_read ], relation.pluck(:last_read)
849849
assert_equal [ topic.written_on ], relation.pluck(:written_on)
850+
assert_equal(
851+
[[topic.written_on, topic.replies_count]],
852+
relation.pluck("min(written_on)", "min(replies_count)")
853+
)
850854
end
851855

852856
def test_pluck_type_cast_with_conflict_column_names
@@ -1224,22 +1228,13 @@ def test_pluck_functions_with_alias
12241228
end
12251229

12261230
def test_pluck_functions_without_alias
1227-
expected = if current_adapter?(:PostgreSQLAdapter)
1228-
# PostgreSQL returns the same name for each column in the given query, so each column is named "coalesce"
1229-
# As a result Rails cannot accurately type cast each value.
1230-
# To work around this, you should use aliases in your select statement (see test_pluck_functions_with_alias).
1231-
[
1232-
["1", "The First Topic"], ["2", "The Second Topic of the day"],
1233-
["3", "The Third Topic of the day"], ["4", "The Fourth Topic of the day"],
1234-
["5", "The Fifth Topic of the day"]
1235-
]
1236-
else
1237-
[
1238-
[1, "The First Topic"], [2, "The Second Topic of the day"],
1239-
[3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"],
1240-
[5, "The Fifth Topic of the day"]
1241-
]
1242-
end
1231+
expected = [
1232+
[1, "The First Topic"],
1233+
[2, "The Second Topic of the day"],
1234+
[3, "The Third Topic of the day"],
1235+
[4, "The Fourth Topic of the day"],
1236+
[5, "The Fifth Topic of the day"]
1237+
]
12431238

12441239
assert_equal expected, Topic.order(:id).pluck(
12451240
Arel.sql("COALESCE(id, 0)"),

0 commit comments

Comments
 (0)