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 送给学长毕业祝福语简短