Skip to content

Commit ad96027

Browse files
committed
Make sure errors.messages works in the same way as Rails 6.1
When there are no errors for a given attribute we were returning empty arrays. We should continue to do that.
1 parent ce795a4 commit ad96027

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

activemodel/lib/active_model/errors.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,18 +228,22 @@ def to_hash(full_messages = false)
228228

229229
undef :to_h
230230

231+
EMPTY_ARRAY = [].freeze # :nodoc:
232+
231233
# Returns a Hash of attributes with an array of their error messages.
232234
def messages
233235
hash = to_hash
236+
hash.default = EMPTY_ARRAY
234237
hash.freeze
238+
hash
235239
end
236240

237241
# Returns a Hash of attributes with an array of their error details.
238242
def details
239243
hash = group_by_attribute.transform_values do |errors|
240244
errors.map(&:details)
241245
end
242-
hash.default = []
246+
hash.default = EMPTY_ARRAY
243247
hash.freeze
244248
hash
245249
end

activemodel/test/cases/errors_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,14 @@ def test_no_key
455455
assert_nil person.errors.as_json.default_proc
456456
end
457457

458+
test "messages returns empty frozen array when when accessed with non-existent attribute" do
459+
errors = ActiveModel::Errors.new(Person.new)
460+
461+
assert_equal [], errors.messages[:foo]
462+
assert_raises(FrozenError) { errors.messages[:foo] << "foo" }
463+
assert_raises(FrozenError) { errors.messages[:foo].clear }
464+
end
465+
458466
test "full_messages doesn't require the base object to respond to `:errors" do
459467
model = Class.new do
460468
def initialize
@@ -621,6 +629,8 @@ def call
621629
errors = ActiveModel::Errors.new(Person.new)
622630

623631
assert_equal [], errors.details[:foo]
632+
assert_raises(FrozenError) { errors.details[:foo] << "foo" }
633+
assert_raises(FrozenError) { errors.details[:foo].clear }
624634
end
625635

626636
test "copy errors" do

0 commit comments

Comments
 (0)