Add slice! method to ActiveModel::Errors

上级 218e50ce
* Add `#slice!` method to `ActiveModel::Errors`.
*Daniel López Prat*
* Fix numericality validator to still use value before type cast except Active Record.
Fixes #33651, #33686.
......
......@@ -112,6 +112,17 @@ def merge!(other)
@details.merge!(other.details) { |_, ary1, ary2| ary1 + ary2 }
end
# Removes all errors except the given keys. Returns a hash containing the removed errors.
#
# person.errors.keys # => [:name, :age, :gender, :city]
# person.errors.slice!(:age, :gender) # => { :name=>["cannot be nil"], :city=>["cannot be nil"] }
# person.errors.keys # => [:age, :gender]
def slice!(*keys)
keys = keys.map(&:to_sym)
@details.slice!(*keys)
@messages.slice!(*keys)
end
# Clear the error messages.
#
# person.errors.full_messages # => ["name cannot be nil"]
......
......@@ -411,6 +411,30 @@ def test_no_key
assert_equal({ name: [{ error: :blank }, { error: :invalid }] }, person.errors.details)
end
test "slice! removes all errors except the given keys" do
person = Person.new
person.errors.add(:name, "cannot be nil")
person.errors.add(:age, "cannot be nil")
person.errors.add(:gender, "cannot be nil")
person.errors.add(:city, "cannot be nil")
person.errors.slice!(:age, "gender")
assert_equal [:age, :gender], person.errors.keys
end
test "slice! returns the deleted errors" do
person = Person.new
person.errors.add(:name, "cannot be nil")
person.errors.add(:age, "cannot be nil")
person.errors.add(:gender, "cannot be nil")
person.errors.add(:city, "cannot be nil")
removed_errors = person.errors.slice!(:age, "gender")
assert_equal({ name: ["cannot be nil"], city: ["cannot be nil"] }, removed_errors)
end
test "errors are marshalable" do
errors = ActiveModel::Errors.new(Person.new)
errors.add(:name, :invalid)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册