Posted about 1 month ago. Visible to the public.

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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Arne Hartherz
Last edit:
about 1 month 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