0
0
Ruby on Railsframework~5 mins

Why validations protect data integrity in Ruby on Rails

Choose your learning style9 modes available
Introduction

Validations check data before saving it. This stops wrong or incomplete data from entering your app.

When you want to make sure a user's email is present and correctly formatted before saving.
When you need to ensure a product's price is a positive number.
When you want to prevent duplicate usernames in your database.
When you want to require that a post has a title before it is saved.
When you want to make sure dates are valid and logical, like an event's end date after its start date.
Syntax
Ruby on Rails
class ModelName < ApplicationRecord
  validates :attribute, validation_type: true
end
Use validates inside your model to add rules for data.
Rails runs these checks automatically before saving data.
Examples
This makes sure the email is not empty before saving a user.
Ruby on Rails
class User < ApplicationRecord
  validates :email, presence: true
end
This ensures the price is a number greater than zero.
Ruby on Rails
class Product < ApplicationRecord
  validates :price, numericality: { greater_than: 0 }
end
This prevents two users from having the same username.
Ruby on Rails
class User < ApplicationRecord
  validates :username, uniqueness: true
end
Sample Program

This example creates an article without a title and with too short content. It checks if the article is valid and prints error messages if not.

Ruby on Rails
class Article < ApplicationRecord
  validates :title, presence: true
  validates :content, length: { minimum: 10 }
end

article = Article.new(title: "", content: "Short")
if article.valid?
  puts "Article is valid"
else
  puts article.errors.full_messages.join(", ")
end
OutputSuccess
Important Notes

Validations run automatically when saving or updating records.

You can add custom validation methods for special rules.

Always validate important data to keep your app reliable and safe.

Summary

Validations stop bad data from entering your app.

They run before saving data to check rules you set.

Use validations to keep your data clean and trustworthy.