Validating presence of an attribute

suggest change

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: If the attribute is a boolean, the usual presence validation does not work (false is blank). Use an inclusion validation:

validates :attribute, inclusion: { in: [true, false] }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents