在模型上,用户有 after_create :apply_role
和 after_update :apply_role
,我想获取 apply_role
方法上回调的当前名称。
类似于:
def apply_role
if callback_name == 'after_create'
# other stuff here
else
# other stuff here
end
end
我知道我可以在 after_create
和 after_update
之间设置不同的方法,但就我而言,在 after_create
和 after_update
上设置方法code> 除了一行之外没有什么不同,所以我想重构我的代码,我只需要一种方法来进行多个回调。
我怎样才能做到这一点?
最佳答案
尝试以下操作,我已经在代码本身的注释中描述了更改。
def User < ActiveRecord::Base
after_save :apply_role # this will gets called in case of create as well as update
def apply_role
if id_changed?
# code to handle newly created record
else
# code to handle updated record
end
end
end
关于ruby-on-rails - 获取回调 ActiveRecord Rails 的当前名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31933990/