Active Record Models, Validations, Associations, Scopes, and Domain Rules
Master the Rails ORM layer and learn how models express business data, constraints, and relationships clearly.
Inside this chapter
- What Active Record Provides
- Model and Validation Example
- Associations
- Scopes and Domain-Focused Queries
Series navigation
Study the chapters in order for the clearest path from Rails beginner concepts to advanced production architecture. Use the previous and next links at the bottom of each page to move through the full tutorial series.
What Active Record Provides
Active Record is the Rails ORM that maps Ruby classes to database tables. It provides querying, persistence, validations, associations, callbacks, scopes, and conventions around naming and schema mapping. It is one of the most productive parts of Rails, but it must be used with discipline to avoid slow queries and bloated models.
Model and Validation Example
class Book < ApplicationRecord
validates :title, presence: true
validates :price, numericality: { greater_than_or_equal_to: 0 }
end
Validations help reject invalid records before they are persisted, but advanced teams also combine validations with database constraints for real safety.
Associations
class Author < ApplicationRecord
has_many :books
end
class Book < ApplicationRecord
belongs_to :author
end
Associations model relationships directly in code. Rails provides helpers for one-to-many, many-to-many, and nested relationship access. Students should learn both the convenience and the query implications of associations.
Scopes and Domain-Focused Queries
class Book < ApplicationRecord
scope :published, -> { where(published: true) }
scope :recent, -> { order(created_at: :desc) }
end
Scopes can keep common query logic expressive and reusable. Strong Rails engineers write scopes that are composable and easy to understand, rather than burying too much behavior in controllers or views.