Overview
When a validation error occurs in a model that inherits from ActiveRecord, determine if a specific validation is responded to.
For example, to check if an attribute in valid? or save has an error.
Prerequisites.
Rails: 5.2
Ruby: 2.5.1
main topic.
Sample User Table Definitions
create_table :users do |t|
t.string :name
t.timestamps
end
Defining the user model
There's a variation of the empty character check for name.
class User < ApplicationRecord
validates :name, presence: true
end
First, instantiate and check validation.
> u = User.new
=> #<User id: nil, name: nil, created_at: nil, updated_at: nil>
> u.valid?
=> false
If you check the error, you'll see the default empty letter error message
> u.errors.full_messages
=> ["Name can't be blank"]
You can use the added? method to find out which validation errors occurred for a particular attribute (from the comments section of this post)
# You can specify the symbol of the attribute name and the type of validation error for the argument.
> u.errors.added?(:name, :blank)
=> true
# If you don't specify the second argument, the default value will be "invalid". Note that the second argument is :invalid
> u.errors.added?(:name)
=> false
[Bonus] Retrieving validation error details
If you want a list of errors, you can run errors.details to see which element and which validation has the error content :blank
> u.errors.details
=> {:name=>[{:error=>:blank}]}
# Returns an array of objects if you give a symbol
u.errors.details[:name]
=> [{:error=>:blank}]
# Return an empty array if you put in an appropriate symbol
> u.errors.details[:name_xxxx]
=> []
In this way, if you specify a symbol from details and check for the presence of a specific symbol:blank in the array to be returned
You can also determine if a particular validation has been responded to, such as added?
> u.errors.details[:name].any? { |d| d[:error] == :blank }
=> true
Top comments (0)