Active Record 模型
验证、回调与迁移。
Active Record 模型
这一课你将能做到
- 写迁移文件建表、改表、加索引,并用
db:rollback安全回滚 - 给模型加验证(presence、uniqueness、自定义),让脏数据进不了数据库
- 声明关联(has_many/belongs_to),用模型回调在保存前后触发业务动作
为什么要学
模型是 Rails 应用的「心脏」。控制器和视图都可以很薄,但模型必须厚——业务规则、数据完整性、对象间关系全在这一层。Active Record 模式的核心思想是:一行数据库记录 = 一个 Ruby 对象,对象身上的方法就是你能对数据做的所有操作。
对比本站:Spring Boot 用 JPA/Hibernate,实体类里要写注解、getter/setter、Repository 接口;Rails 的模型类继承 ApplicationRecord 就什么都有了——属性读写、查询接口、验证、关联,零注解零模板代码。这是 Ruby 动态语言特性带来的红利,也是理解「约定优于配置」最好的样本。
先建立图像
模型与表的约定映射:
Ruby 世界 数据库世界
───────────── ─────────────
class Article 表 articles
title ←───────────────────── 列 title VARCHAR
body ←───────────────────── 列 body TEXT
save ─────────────────────► INSERT INTO ...
find(1) ────────────────────► SELECT * WHERE id=1
destroy ────────────────────► DELETE WHERE id=1
Article.has_many :comments ──► comments.article_id 外键
Comment.belongs_to :article ──► 同上,反向视角
一条记录的完整生命周期(回调挂载点):
new → validation → save → 数据库
│ │
before_validation before_save → before_create
after_validation after_create → after_save
跟着做
步骤 1:用迁移建表
bin/rails generate model Article title:string body:text published:boolean
生成的迁移文件 db/migrate/2026xxxxxxxx_create_articles.rb:
class CreateArticles < ActiveRecord::Migration[7.1]
def change
create_table :articles do |t|
t.string :title
t.text :body
t.boolean :published, default: false, null: false
t.timestamps # created_at + updated_at 两列
end
end
end
执行并验证:
bin/rails db:migrate
bin/rails console
Article.column_names # => ["id", "title", "body", "published", "created_at", "updated_at"]
步骤 2:改表与回滚
发现需要给标题加唯一索引:
bin/rails generate migration AddIndexToArticlesTitle
class AddIndexToArticlesTitle < ActiveRecord::Migration[7.1]
def change
add_index :articles, :title, unique: true
end
end