Rails:around_*回调

gjb*_*gjb 89 ruby ruby-on-rails callback

我已经阅读了http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html上的文档,但是不知道何时around_*触发了关于before_*和的回调after_*.

任何帮助非常感谢.

谢谢.

Jac*_*kin 167

around_*在操作之前调用回调,然后当您想要调用操作本身时,您yield需要它,然后继续执行.这就是为什么它被称为around

顺序是这样的:before,around,after.

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

def around_save
   #do something...
   yield #saves
   #do something else...
end
Run Code Online (Sandbox Code Playgroud)

  • 那讲得通.谢谢! (5认同)
  • 这是有道理的,不在官方 Rails 指南中。 (5认同)

Pan*_*kos 113

围绕操作以及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
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,这是最有启发性的答案.谢谢你,朋友. (12认同)