Posted 12 days ago. Visible to the public.

Rails: How to find out which model 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).

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
12 days ago
by Arne Hartherz
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