ruby - Rails:around_ *回调

我已经在http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html上阅读了这些文档,但是不明白around_*回调是什么时候触发before_*after_*

任何帮助非常感谢。

谢谢。

gjb asked 2019-09-10T05:19:35Z
2个解决方案
162 votes

around_save回调在操作之前被调用,然后当你想调用动作本身时,你around,然后继续执行。 这就是为什么它被称为around_save

订单如下:around_save,around,after

所以,典型的around_save看起来像这样:

def around_save
   #do something...
   yield #saves
   #do something else...
end
Jacob Relkin answered 2019-09-10T05:20:04Z
108 votes

围绕操作以及before_ *和after_ *操作内部调用around_ *回调。 例如:

class User
  def before_save
    puts 'before save'
  end

  def after_save
    puts 'after_save'
  end

  def around_save
    puts 'in around save'
    yield # User saved
    puts 'out around save'
  end
end

User.save
  before save
  in around save
  out around save
  after_save
=> true
Pan Thomakos answered 2019-09-10T05:20:29Z
translate from https://stackoverflow.com:/questions/4998553/rails-around-callbacks