0
0
RailsHow-ToBeginner · 3 min read

How to Use Validations in Rails Model in Ruby on Rails

In Ruby on Rails, use validates methods inside your model class to add validations that check data before saving. Common validations include presence, uniqueness, length, and format, which help keep your data clean and consistent.
📐

Syntax

Use validates inside your model class to specify rules for attributes. The general pattern is validates :attribute, validation_type: options. You can add multiple validations for different attributes.

Example validations include presence: true to require a value, uniqueness: true to ensure no duplicates, and length: { minimum: 3 } to set size limits.

ruby
class User < ApplicationRecord
  validates :name, presence: true
  validates :email, presence: true, uniqueness: true
  validates :password, length: { minimum: 6 }
end
💻

Example

This example shows a User model with validations for name, email, and password. It prevents saving users without a name or email, ensures emails are unique, and requires passwords to be at least 6 characters long.

ruby
class User < ApplicationRecord
  validates :name, presence: true
  validates :email, presence: true, uniqueness: true
  validates :password, length: { minimum: 6 }
end

# Usage in Rails console or controller
user = User.new(name: '', email: 'test@example.com', password: '123')
user.valid? # => false
user.errors.full_messages # => ["Name can't be blank", "Password is too short (minimum is 6 characters)"]

user.name = 'Alice'
user.password = 'secret123'
user.valid? # => true
user.save # saves the user to the database
Output
false ["Name can't be blank", "Password is too short (minimum is 6 characters)"] true true
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to call valid? or check errors before saving.
  • Using validations on attributes that don't exist in the model.
  • Not handling validation failures in controllers or views, causing silent errors.
  • Using uniqueness without a database index, which can cause race conditions.

Always add database constraints for critical validations like uniqueness.

ruby
class Product < ApplicationRecord
  # Wrong: typo in attribute name
  validates :prize, presence: true

  # Right:
  validates :price, presence: true
end
📊

Quick Reference

ValidationPurposeExample
presenceEnsures attribute is not emptyvalidates :name, presence: true
uniquenessEnsures attribute is unique in DBvalidates :email, uniqueness: true
lengthChecks string length limitsvalidates :password, length: { minimum: 6 }
formatValidates attribute matches regexvalidates :email, format: { with: /@/ }
numericalityChecks if value is a numbervalidates :age, numericality: { only_integer: true }

Key Takeaways

Use validates in your Rails model to enforce data rules before saving.
Common validations include presence, uniqueness, length, format, and numericality.
Always check valid? and handle errors before saving records.
Add database indexes for uniqueness validations to avoid race conditions.
Avoid typos in attribute names to ensure validations work correctly.