Rails模型中around_create回调的目的是什么?

Mad*_*hik 14 ruby model callback ruby-on-rails-3

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

Gab*_*azo 33

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

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
Run Code Online (Sandbox Code Playgroud)


Joh*_*ler 0

around_createnew?当保存带有该标志的模型时调用。它可用于添加数据以添加/更改模型的值、调用其他方法等...我无法想到此回调的特定用例,但它完成了一组“之前、之后、周围”创建操作的回调。对于查找、更新、保存和删除事件有类似的“之前、之后、周围”回调集。