提交 9848c463 编写于 作者: E Esteban Pastorino

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:
https://github.com/rails/rails/commit/b97035df64f5b2f912425c4a7fcb6e6bb3ddab8d
(Added in Rails 4.1)
and
https://github.com/rails/rails/commit/6ec8ba16d85d5feaccb993c9756c1edcbbf0ba13#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?
上级 00a0388a
......@@ -110,7 +110,7 @@ def clear
# 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?
......
......@@ -128,6 +128,13 @@ def test_no_key
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!
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册