Validating presence of an attribute

This helper validates that the specified attributes are not empty.

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

Person.create(name: "John").valid? # => true
Person.create(name: nil).valid? # => false

You can use the absence helper to validate that the specified attributes are absent. It uses the present?method to check for nil or empty values.

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

Note: In case the attribute is a boolean one, you cannot make use of the usual presence validation (the attribute would not be valid for a false value). You can get this done by using an inclusion validation:

validates :attribute, inclusion: [true, false]

results matching ""

    No results matching ""