From ff0204bc7f5b33a04cfe4f053e3f24a65f0faff5 Mon Sep 17 00:00:00 2001 From: Edouard CHIN Date: Tue, 23 Jul 2019 17:58:59 +0200 Subject: Modify behaviour of `AM::Errors#to_h`: - `AM::Error#to_h` was kind of broken before and would return in the hash values a single error message. ```ruby person = Person.new person.errors.add(:name, "cannot be blank") person.errors.add(:name, "too long") puts person.errors.to_h # {name: 'too long'} ``` Since an attribute can have different errors, the previous behavior didn't make much sense. Now, `ActiveModel::Errors#to_hash` correctly returns an array of error messages containing all the errors for an attribute. However, one can easily be surprised by this change, so let's deprecated it first. --- activemodel/lib/active_model/errors.rb | 8 ++++++-- activemodel/test/cases/errors_test.rb | 5 +++-- 2 files changed, 9 insertions(+), 4 deletions(-) (limited to 'activemodel') diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index e7405fb586..480f24183a 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -304,9 +304,13 @@ module ActiveModel end def to_h - deprecation_rename_warning(:to_h, :to_hash) + ActiveSupport::Deprecation.warn(<<~EOM) + ActiveModel::Errors#to_h is deprecated and will be removed in Rails 6.2 + Please use `ActiveModel::Errors.to_hash` instead. The values in the hash + returned by `ActiveModel::Erors.to_hash` is an array of error messages. + EOM - to_hash + to_hash.transform_values { |values| values.last } end def messages diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb index 79ccfe0c13..a6cd1da717 100644 --- a/activemodel/test/cases/errors_test.rb +++ b/activemodel/test/cases/errors_test.rb @@ -477,10 +477,11 @@ class ErrorsTest < ActiveModel::TestCase test "to_h is deprecated" do person = Person.new person.errors.add(:name, "cannot be blank") + person.errors.add(:name, "too long") - expected_deprecation = "ActiveModel::Errors#to_h is deprecated. Please call #to_hash instead." + expected_deprecation = "ActiveModel::Errors#to_h is deprecated" assert_deprecated(expected_deprecation) do - assert_equal({ name: ["cannot be blank"] }, person.errors.to_h) + assert_equal({ name: "too long" }, person.errors.to_h) end end -- cgit v1.2.3