Rails 模型中 around_create 回调的目的是什么? [英] What is purpose of around_create callback in Rails Model?

查看:17
本文介绍了Rails 模型中 around_create 回调的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

around_create 回调代码是什么时候执行的,我们应该在什么情况下使用它?

when is around_create callback code executed, in what situations we should use it?

推荐答案

也有这个问题,现在找到了答案:around_create 允许您基本上同时执行 before_createafter_create 在一种方法中.您必须使用 yield 在两者之间执行保存.

Had this question, too, and have now found the answer: around_create allows you to basically do both a before_create and an after_create in one method. You have to use yield to execute the save in between.

class MyModel < ActiveRecord::Base
  around_create :my_callback_method

  private
    def my_call_back_method
      # do some "before_create" stuff here

      yield  # this makes the save happen

      # do some "after_create" stuff here
    end
end

这篇关于Rails 模型中 around_create 回调的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆