1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Do not create a hash key when calling ActiveModel::Errors#include?

From: https://github.com/rails/rails/issues/24279

Problem:
By doing `record.errors.include? :foo`, it adds a new key to the
@messages hash that defaults to an empty array.

This happens because of a combination of these 2 commits:
b97035df64
(Added in Rails 4.1)
and
6ec8ba16d8 (diff-fdcf8b65b5fb954372c6fe1ddf284c78R76)
(Rails 5.0)

By adding the default proc that returns an array for non-existing keys,
ruby adds that key to the hash.

Solution:
Change `#include?` to check with `has_key?` and then check if that value is
`present?`.

Add test case for ActiveModels::Errors#include?
This commit is contained in:
Esteban Pastorino 2016-03-24 10:27:31 -04:00
parent 00a0388adc
commit 9848c4632f
2 changed files with 8 additions and 1 deletions

View file

@ -110,7 +110,7 @@ module ActiveModel
# person.errors.include?(:name) # => true
# person.errors.include?(:age) # => false
def include?(attribute)
messages[attribute].present?
messages.key?(attribute) && messages[attribute].present?
end
alias :has_key? :include?
alias :key? :include?

View file

@ -128,6 +128,13 @@ class ErrorsTest < ActiveModel::TestCase
assert !person.errors.include?(:foo)
end
test "include? does not add a key to messages hash" do
person = Person.new
person.errors.include?(:foo)
assert_not person.errors.messages.key?(:foo)
end
test "adding errors using conditionals with Person#validate!" do
person = Person.new
person.validate!