![](/img/trans.png)
[英]How to get Devise's current_user in ActiveRecord callback in Rails?
[英]Get Current Name Of Callback ActiveRecord Rails
在模型上,用户具有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
上的方法除了一行外没有其他区别,因此我想重构我的代码,并且只需要一种方法进行多次回调。
我怎样才能做到这一点?
尝试下面的内容,我已经描述了代码本身中注释的变化。
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
要回答您的问题,您将使用id_changed?
确定您是在after_save
( true
)还是after_update
( false
)回调中。
像这样:
def apply_role
if id_changed?
# created
else
# updated
end
end
虽然通常这不是完成的方式。 最好将它们拆分为单独的方法,并在其相应的回调中使用适当的方法。
像这样:
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.