Posted 4 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.

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

And let's assume we have a blank user:

Copy
user = User.new user.valid? # => false

The record's errors then contains all validation errors:

Copy
>> 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:

Copy
>> 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).

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
4 months ago
by Dominik Schöler
Keywords:
ActiveRecord, ActiveModel, attributes, fields
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