0
0
Ruby on Railsframework~5 mins

Presence validation in Ruby on Rails

Choose your learning style9 modes available
Introduction

Presence validation checks if a value is given before saving data. It helps avoid empty or missing important information.

When you want to make sure a user enters their name before signing up.
When a product must have a price before it is saved in the store.
When a blog post needs a title before publishing.
When a form field cannot be left blank to keep data complete.
Syntax
Ruby on Rails
validates :attribute_name, presence: true
Replace :attribute_name with the name of the field you want to check.
This validation runs automatically before saving the record.
Examples
This ensures the email field is not empty before saving.
Ruby on Rails
validates :email, presence: true
This makes sure the username is provided.
Ruby on Rails
validates :username, presence: true
This requires a title to be present for a blog post.
Ruby on Rails
validates :title, presence: true
Sample Program

This example shows a User model that requires a name. When the name is empty, validation fails and shows an error. When the name is set, validation passes.

Ruby on Rails
class User < ApplicationRecord
  validates :name, presence: true
end

user = User.new(name: "")
puts user.valid? # false
puts user.errors.full_messages # ["Name can't be blank"]

user.name = "Alice"
puts user.valid? # true
puts user.errors.full_messages # []
OutputSuccess
Important Notes

Presence validation only checks if the value is not blank. It does not check format or length.

Use validates inside your model class to add presence validation.

Summary

Presence validation ensures important fields are not empty.

It helps keep data complete and reliable.

Use validates :field, presence: true in your model.