热门面试题与答案和在线测试
面向面试准备、在线测试、教程与实战练习的学习平台

通过聚焦学习路径、模拟测试和面试实战内容持续提升技能。

WithoutBook 将分主题面试题、在线练习测试、教程和对比指南整合到一个响应式学习空间中。

Chapter 5

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

  1. What Active Record Provides
  2. Model and Validation Example
  3. Associations
  4. 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.

Tutorial Home

Chapter 5

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.

Chapter 5

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.

Chapter 5

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.

Chapter 5

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.

版权所有 © 2026,WithoutBook。