0
0
RailsHow-ToBeginner · 3 min read

How to Use Presence Validation in Ruby on Rails

In Ruby on Rails, use validates :attribute, presence: true inside your model to ensure that the attribute is not empty or nil before saving. This validation prevents records from being saved without required data.
📐

Syntax

The presence validation uses the validates method with the presence: true option inside a model class. This tells Rails to check that the specified attribute is not blank or nil before saving.

  • validates: method to add validations
  • :attribute: the name of the field to validate
  • presence: true: option to require the attribute to be present
ruby
class User < ApplicationRecord
  validates :name, presence: true
end
💻

Example

This example shows a User model with presence validation on the email attribute. It prevents saving a user without an email.

ruby
class User < ApplicationRecord
  validates :email, presence: true
end

user = User.new(email: '')
user.valid? # => false
user.errors.full_messages # => ["Email can't be blank"]

user.email = 'user@example.com'
user.valid? # => true
user.save # => true
Output
false ["Email can't be blank"] true true
⚠️

Common Pitfalls

Common mistakes include:

  • Using validates_presence_of (older syntax) instead of validates :attribute, presence: true.
  • Expecting presence validation to check for format or length; it only checks if the value is not blank.
  • Not handling validation errors in the controller or view, which can confuse users.
ruby
class Product < ApplicationRecord
  # Wrong (legacy syntax):
  # validates_presence_of :title

  # Correct modern syntax:
  validates :title, presence: true
end
📊

Quick Reference

Validation OptionDescription
presence: trueEnsures attribute is not nil or empty string
validates :attr, presence: trueModern syntax to add presence validation
errors.full_messagesShows validation error messages
valid?Checks if model passes validations

Key Takeaways

Use validates :attribute, presence: true inside your model to require a value.
Presence validation only checks that the attribute is not blank or nil.
Always handle validation errors to inform users why saving failed.
Use modern syntax instead of legacy validation methods.
Check model validity with valid? before saving.