Ruby on rails 获取回调ActiveRecord Rails的当前名称
在模型上,用户在创建:应用角色之后有Ruby on rails 获取回调ActiveRecord Rails的当前名称,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,在模型上,用户在创建:应用角色之后有,在更新:应用角色之后有,我想在应用角色方法上获得回调的当前名称 比如: def apply_role if callback_name == 'after_create' # other stuff here else # other stuff here end end 我知道我可以在创建之后的和更新之后的之间设置不同的方法,但是在我的例子中,创建之后的和更新之后的的方法除了一行之外没有什么不同,所以我想重构我的代码,我只需要一个方
,在更新:应用角色之后有,我想在应用角色
方法上获得回调的当前名称
比如:
def apply_role
if callback_name == 'after_create'
# other stuff here
else
# other stuff here
end
end
我知道我可以在创建之后的和更新之后的之间设置不同的方法,但是在我的例子中,创建之后的和更新之后的的方法除了一行之外没有什么不同,所以我想重构我的代码,我只需要一个方法进行多次回调
我该怎么做?要回答您的问题,您可以使用id\u changed?
来确定在保存(true
)或更新(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
请尝试以下内容,我已经描述了代码本身注释中的更改
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
def User
如果它被成功保存(因此在保存后的中),那么将始终保持为true
,因此在本例中,“新创建的”代码将始终运行,即使在更新时也是如此。