Skip to content

Commit 16510d6

Browse files
Kachegmcgibbon
authored andcommitted
Deprecate ActiveRecord::Result#to_hash in favor of #to_a
method returns an array of hashes, not a hash e.g. Hash.try_convert(result) calls #to_hash and raises a TypeError [Gannon McGibbon + Kevin Cheng]
1 parent e925cb4 commit 16510d6

File tree

4 files changed

+27
-5
lines changed

4 files changed

+27
-5
lines changed

activerecord/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Deprecate `ActiveRecord::Result#to_hash` in favor of `ActiveRecord::Result#to_a`.
2+
3+
*Gannon McGibbon*, *Kevin Cheng*
4+
15
* SQLite3 adapter supports expression indexes.
26

37
```

activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -576,7 +576,7 @@ def table_structure_with_collation(table_name, basic_structure)
576576
column
577577
end
578578
else
579-
basic_structure.to_hash
579+
basic_structure.to_a
580580
end
581581
end
582582

activerecord/lib/active_record/result.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ module ActiveRecord
2121
# ]
2222
#
2323
# # Get an array of hashes representing the result (column => value):
24-
# result.to_hash
24+
# result.to_a
2525
# # => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
2626
# {"id" => 2, "title" => "title_2", "body" => "body_2"},
2727
# ...
@@ -66,10 +66,18 @@ def each
6666
end
6767

6868
# Returns an array of hashes representing each row record.
69-
def to_hash
69+
def to_a
7070
hash_rows
7171
end
7272

73+
def to_hash
74+
ActiveSupport::Deprecation.warn(<<-MSG.squish)
75+
`ActiveRecord::Result#to_hash` has been renamed to `to_a`.
76+
`to_hash` is deprecated and will be removed in Rails 6.1.
77+
MSG
78+
to_a
79+
end
80+
7381
alias :map! :map
7482
alias :collect! :map
7583

activerecord/test/cases/result_test.rb

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,22 @@ def result
2121
assert_equal 3, result.length
2222
end
2323

24-
test "to_hash returns row_hashes" do
24+
test "to_a returns row_hashes" do
2525
assert_equal [
2626
{ "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" },
2727
{ "col_1" => "row 2 col 1", "col_2" => "row 2 col 2" },
2828
{ "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" },
29-
], result.to_hash
29+
], result.to_a
30+
end
31+
32+
test "to_hash (deprecated) returns row_hashes" do
33+
assert_deprecated do
34+
assert_equal [
35+
{ "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" },
36+
{ "col_1" => "row 2 col 1", "col_2" => "row 2 col 2" },
37+
{ "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" },
38+
], result.to_hash
39+
end
3040
end
3141

3242
test "first returns first row as a hash" do

0 commit comments

Comments
 (0)