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) and6ec8ba16d8 (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:
parent
00a0388adc
commit
9848c4632f
2 changed files with 8 additions and 1 deletions
|
@ -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?
|
||||
|
|
|
@ -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!
|
||||
|
|
Loading…
Reference in a new issue