I'm playing around with the new Rails 3 API and I have a question regarding the new method run_callbacks(kind, *args, &block)
In 开发者_开发问答the following code:
class User < ActiveRecord::Base
before_save :say_hi
after_save :say_bye
private
def say_hi; puts "hi"; end
def say_bye; puts "bye"; end
end
I can explicit call the callbacks on save by running:
> u.run_callbacks(:save)
hi
bye
=> true
But my question is, how I can only run the before_save or after_save callback?
Reviewing the run_callbacks(kind, *args, &block)
code:
# File activesupport/lib/active_support/callbacks.rb, line 92
def run_callbacks(kind, *args, &block)
send("_run_#{kind}_callbacks", *args, &block)
end
I don't know how to build *args
to only call before or after callbacks, I tried something like u.run_callbacks(:before_save)
(gives me undefined method error) and u.run_callbacks(:save, :before)
runs all the save callbacks (before and after).
Looks like you are running into a bug in Rails 3.0. It appears to be in the queue for 3.0.1 as mentioned in this lighthouse ticket.
As @venables says, you can at least get the before_save callbacks to fire by sending false
to run_callbacks(:save)
.
I'm still looking into how to do the after_save only, but to run JUST the before_save callback, you can do something like:
u.run_callbacks(:save) { false }
This should cancel the callbacks after the before_save ones are run.
精彩评论