DEV Community

@kon_yu
@kon_yu

Posted on

3 3

Determine if a particular validation error is occurring in AcitiveRecord

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay