4

在 Rails 3.0.5 和 Ruby 1.9.3 中,是否可以around_save在声明中定义回调的主体around_save

也就是说,我注意到这种情况正常工作:

around_save :around_save_body
def around_save_body
  puts 'before save'
  yield 
  puts 'after save'
end

[114] pry(main)> a = Activity.find(57)
=> #<Activity id: 57, ... >

[115] pry(main)> a.save
before save
after save
=> true

而如果我将正文内联,我会得到一个 LocalJumpError:

around_save do |activity|
  puts 'before save'
  yield 
  puts 'after save'
end

[117] pry(main)> a = Activity.find(57)
=> #<Activity id: 57, ... >

[118] pry(main)> a.save
before save
LocalJumpError: no block given (yield)
from /home/maksim/hkn/website/app/models/activity.rb:47:in `block in <class:Activity>'

我尝试在第二个示例中更改yieldyield activity,但得到了相同的结果。是否可以让我的around_save身体符合around_save声明?

4

1 回答 1

11

在这种情况下ActiveRecord,将 aProc作为第二个参数传递,只需执行以下操作:

around_save do |activity, block|
  puts 'before save'
  block.call
  puts 'after save'
end
于 2012-07-12T00:26:14.803 回答