Posted 11 months ago. Visible to the public. Linked content.

Rails: How to check if a certain validation failed

If validations failed for a record, and you want to find out if a specific one failed, you can do this via Rails.
You should rarely need this, as your error messages are usually good enough to display all necessary information to users.

As an example, consider the following model which uses two validations on the email attribute.

class User < ApplicationRecord validates :email, presence: true, uniqueness: true end

And let's assume we have a blank user:

user = user.valid? # => false

The record's errors then contains all validation errors:

>> user.errors => #<ActiveModel::Errors @base=#<User ...>, @messages={:email=>["can't be blank"]}, @details={:email=>[{:error=>:blank}]}>

Instead dissecting error.details yourself to figure out which email validation failed, use the added? method:

>> user.errors.added?(:email, :blank) => true >> user.errors.added?(:email, :taken) => false

Note how error types don't necessarily match the validation name (:blank for :presence, :taken for :uniqueness).

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Arne Hartherz
Last edit:
4 months ago
by Arne Hartherz
ActiveRecord, ActiveModel, attributes, fields, errors
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more