Validations and Queries
Data integrity and querying.
Why Validate?
Validations guard your data before it reaches the database. They run when you save a record and reject invalid data with helpful messages.
- They keep bad data out (missing names, malformed emails).
- They run in Ruby, so messages are easy to show users.
- They complement, not replace, database constraints.
Presence Validation
The most common rule is validates :field, presence: true, which requires a non-blank value. Saving without it fails and records an error.
class User < ApplicationRecord
validates :name, presence: true
end
# User.create(name: "") fails to saveAll lessons in this course
- Active Record Basics
- Migrations
- Associations
- Validations and Queries