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

Merge pull request #38903 from HParker/add-access-to-attributes-on-errors

Add attribute_names method on errors
This commit is contained in:
Rafael França 2020-04-08 19:18:11 -04:00 committed by GitHub
commit 46cb94f6ed
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 0 deletions

View file

@ -264,6 +264,14 @@ module ActiveModel
keys.freeze
end
# Returns all error attribute names
#
# person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
# person.errors.attribute_names # => [:name]
def attribute_names
@errors.map(&:attribute).uniq.freeze
end
# Returns an xml formatted representation of the Errors hash.
#
# person.errors.add(:name, :blank, message: "can't be blank")

View file

@ -167,6 +167,30 @@ class ErrorsTest < ActiveModel::TestCase
end
end
test "attribute_names returns the error attributes" do
errors = ActiveModel::Errors.new(Person.new)
errors.add(:foo, "omg")
errors.add(:baz, "zomg")
assert_equal [:foo, :baz], errors.attribute_names
end
test "attribute_names only returns unique attribute names" do
errors = ActiveModel::Errors.new(Person.new)
errors.add(:foo, "omg")
errors.add(:foo, "zomg")
assert_equal [:foo], errors.attribute_names
end
test "attribute_names returns an empty array after try to get a message only" do
errors = ActiveModel::Errors.new(Person.new)
errors.messages[:foo]
errors.messages[:baz]
assert_equal [], errors.attribute_names
end
test "detecting whether there are errors with empty?, blank?, include?" do
person = Person.new
person.errors[:foo]