This blog is part of our Rails 6 series.
Rails 6 added of_kind? on ActiveModel::Errors. It returns true if the ActiveModel::Errors object has provided a key and message associated with it. The default message is :invalid.
of_kind? is same as ActiveModel::Errors#added? but, it doesn't take extra options as a parameter.
Let's checkout how it works.
Rails 6.0.0.beta2
1>> class User < ApplicationRecord 2>> validates :name, presence: true 3>> end 4 5>> user = User.new 6 7=> => #<User id: nil, name: nil, password: nil, created_at: nil, updated_at: nil> 8 9>> user.valid? 10 11=> false 12 13>> user.errors 14 15=> #<ActiveModel::Errors:0x00007fc462a1d140 @base=#<User id: nil, name: nil, password: nil, created_at: nil, updated_at: nil>, @messages={:name=>["can't be blank"]}, @details={:name=>[{:error=>:blank}]}> 16 17>> user.errors.of_kind?(:name) 18 19=> false 20 21>> user.errors.of_kind?(:name, :blank) 22 23=> true 24 25>> user.errors.of_kind?(:name, "can't be blank") 26 27=> true 28 29>> user.errors.of_kind?(:name, "is blank") 30 31=> false
Here is the relevant pull request.