Ruby on Rails 回调简介
示例
回调是一种在对象生命周期的特定时刻(在从数据库创建,删除,更新,验证,保存或加载之前或之后)被调用的方法。
例如,假设您的列表在创建后30天内到期。
一种方法是这样的:
class Listing < ApplicationRecord
after_create :set_expiry_date
private
def set_expiry_date
expiry_date =Date.today+ 30.days
self.update_column(:expires_on, expiry_date)
end
end回调的所有可用方法如下,在每个对象操作期间调用它们的顺序相同:
创建一个对象
before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
after_commit/after_rollback
更新对象
before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save
after_commit/after_rollback
销毁对象
before_destroy
around_destroy
after_destroy
after_commit/after_rollback
注意:after_save可以同时在create和update上运行,但无论执行宏调用的顺序如何,始终在更具体的回调after_create和after_update之后。
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短