Rails模型回调机制 #
一、回调概述 #
1.1 什么是回调 #
回调是在模型生命周期的特定时刻自动执行的方法。
1.2 回调类型 #
| 回调 | 说明 |
|---|---|
| before_validation | 验证前 |
| after_validation | 验证后 |
| before_save | 保存前 |
| after_save | 保存后 |
| before_create | 创建前 |
| after_create | 创建后 |
| before_update | 更新前 |
| after_update | 更新后 |
| before_destroy | 删除前 |
| after_destroy | 删除后 |
二、注册回调 #
2.1 基本用法 #
ruby
class Article < ApplicationRecord
before_save :normalize_title
after_create :send_notification
private
def normalize_title
self.title = title.downcase.titleize
end
def send_notification
NotificationMailer.article_created(self).deliver_later
end
end
三、条件回调 #
3.1 条件执行 #
ruby
class Article < ApplicationRecord
before_save :publish_notification, if: :published?
private
def published?
status == 'published'
end
end
四、回调事务 #
4.1 事务回滚 #
ruby
class Article < ApplicationRecord
after_create :log_creation
private
def log_creation
raise ActiveRecord::Rollback unless valid?
end
end
五、总结 #
5.1 核心要点 #
| 要点 | 说明 |
|---|---|
| 生命周期 | 创建/更新/删除 |
| 注册回调 | before_xxx/after_xxx |
| 条件回调 | if/unless |
| 事务回滚 | raise Rollback |
5.2 下一步 #
现在你已经掌握了回调机制,接下来让我们学习 表单基础,深入了解Rails的表单处理!
最后更新:2026-03-28