简体   繁体   English

获取回调ActiveRecord Rails的当前名称

[英]Get Current Name Of Callback ActiveRecord Rails

On model User have after_create :apply_role and after_update :apply_role , and I want to get current name of callback on apply_role method. 在模型上,用户具有after_create :apply_roleafter_update :apply_role ,我想在apply_role方法上获取回调的当前名称。

something like : 就像是 :

def apply_role
 if callback_name == 'after_create'
    # other stuff here
 else
    # other stuff here
 end
end

I know I can set different method between after_create and after_update , but in my case method on after_create and after_update not different except one line, so I want refactor my code and I just need one method for multiple callback. 我知道我可以在after_createafter_update之间设置不同的方法,但是在我的情况下, after_createafter_update上的方法除了一行外没有其他区别,因此我想重构我的代码,并且只需要一种方法进行多次回调。

How can I do that? 我怎样才能做到这一点?

Try following, I have described the changes in comments in the code itself. 尝试下面的内容,我已经描述了代码本身中注释的变化。

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

To answer your question, you'd use id_changed? 要回答您的问题,您将使用id_changed? to determine if you are in a after_save ( true ) or after_update ( false ) callback. 确定您是在after_savetrue )还是after_updatefalse )回调中。

Like this: 像这样:

def apply_role
  if id_changed?
    # created
  else
    # updated
  end
end

Though that is generally not the way it is done. 虽然通常这不是完成的方式。 It would be better to split those into separate methods and use the proper method with its corresponding callback. 最好将它们拆分为单独的方法,并在其相应的回调中使用适当的方法。

Something like this: 像这样:

after_create :apply_role
after_update :update_role

def apply_role
  # do stuff
end

def update_role
  # do other stuff
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM