Rails: Active Record Validations (Part 2)

Validation Helpers

Active Record offers many pre defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object’s errors collection, and this message is associated with the attribute being validated. Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.

acceptance

This method validates that a checkbox on the user interface was checked when a form was submitted. This is typically used when the user needs to agree to your application’s terms of service, confirm that some text is read, or any similar concept.

class Person < ApplicationRecord
validates :terms_of_service, acceptance: true
end

This check is performed only if terms_of_service is not nil . The default error message for this helper is "must be accepted". You can also pass custom message via the message option.

validates_associated

You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, valid? will be called upon each one of the associated objects.

class Library < ApplicationRecord
has_many :books
validates_associated :books
end

confirmation

You should use this helper when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute whose name is the name of the field that has to be confirmed with “_confirmation” appended.

class Person < ApplicationRecord
validates :email, confirmation: true
end

In your view template you could use something like

<%= text_field :person, :email %>
<%= text_field :person, :email_confirmation %>

This check is performed only if email_confirmation is not nil. To require confirmation, make sure to add a presence check for the confirmation attribute.

exclusion

This helper validates that the attributes’ values are not included in a given set. In fact, this set can be any enumerable object.

class Account < ApplicationRecord
validates :subdomain, exclusion: { in: %w(www us ca jp),
message: "%{value} is reserved." }
end

The exclusion helper has an option :in that receives the set of values that will not be accepted for the validated attributes. The :in option has an alias called :within that you can use for the same purpose, if you'd like to.

format

This helper validates the attributes’ values by testing whether they match a given regular expression, which is specified using the :with option.

class Product < ApplicationRecord
validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/,
message: "only allows letters" }
end

Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option.

inclusion

This helper validates that the attributes’ values are included in a given set. In fact, this set can be any enumerable object.

class Coffee < ApplicationRecord
validates :size, inclusion: { in: %w(small medium large),
message: "%{value} is not a valid size" }
end

The inclusion helper has an option :in that receives the set of values that will be accepted. The :in option has an alias called :within that you can use for the same purpose, if you'd like to.

length

This helper validates the length of the attributes’ values. It provides a variety of options, so you can specify length constraints in different ways:

class Person < ApplicationRecord
validates :name, length: { minimum: 2 }
validates :bio, length: { maximum: 500 }
validates :password, length: { in: 6..20 }
validates :registration_number, length: { is: 6 }
end

The possible length constraint options are:

  • :minimum - The attribute cannot have less than the specified length.
  • :maximum - The attribute cannot have more than the specified length.
  • :in (or :within) - The attribute length must be included in a given interval. The value for this option must be a range.
  • :is - The attribute length must be equal to the given value.

presence

This helper validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.

class Person < ApplicationRecord
validates :name, :login, :email, presence: true
end

If you want to be sure that an association is present, you’ll need to test whether the associated object itself is present, and not the foreign key used to map the association. This way, it is not only checked that the foreign key is not empty but also that the referenced object exists.

class Supplier < ApplicationRecord
has_one :account
validates :account, presence: true
end

absence

This helper validates that the specified attributes are absent. It uses the present? method to check if the value is not either nil or a blank string, that is, a string that is either empty or consists of whitespace.

class Person < ApplicationRecord
validates :name, :login, :email, absence: true
end

If you want to be sure that an association is absent, you’ll need to test whether the associated object itself is absent, and not the foreign key used to map the association.

class LineItem < ApplicationRecord
belongs_to :order
validates :order, absence: true
end

In order to validate associated records whose absence is required, you must specify the :inverse_of option for the association:

class Order < ApplicationRecord
has_many :line_items, inverse_of: :order
end

These were some examples of how validations can be applied in rails, for more you can refer to https://guides.rubyonrails.org/active_record_validations.html.

Also don’t forget to 👏and leave comments in the comment section.

--

--