Ruby on rails 对于具有多个方法的回调,只执行一次条件方法。轨道
在Rails应用程序中,我使用了一个after_update回调,该回调在传递条件方法时运行多个方法,如下所示: app/models/my_model.rbRuby on rails 对于具有多个方法的回调,只执行一次条件方法。轨道,ruby-on-rails,callback,Ruby On Rails,Callback,在Rails应用程序中,我使用了一个after_update回调,该回调在传递条件方法时运行多个方法,如下所示: app/models/my_model.rb class MyModel
class MyModel
我注意到方法发生这种情况?
执行了三次,就在:method\u 1
,:method\u 2
,:method\u 3
之前
这是有意义的,因为这三种回调方法中的任何一种都可能以这样的方式更改数据,即必须再次评估条件,以确保在每种情况下都满足条件。但是,当您知道这3种方法不会以任何方式更改数据,从而改变条件评估时,是否可以只运行一次以获得一些效率
我似乎在网上找不到任何东西,不知道是否有人能给我建议
另外,使用Rails 5.1封装是克服这种情况的最简单方法之一
只需将您的方法包装到另一个方法中,那么它只会检查一次这种情况?
class MyModel < ApplicationRecord
after_update :combine_methods, if: :this_happens?
#some custom methods
private
def combine_methods
method_1
method_2
method_3
end
def this_happens?
# a condition that returns true or false here
end
end
class MyModel
谢谢mdegis。当然我一直在寻找一个内置的解决方案,但你的方式是有意义的。我怎么没想到呢!
class MyModel < ApplicationRecord
after_update :combine_methods, if: :this_happens?
#some custom methods
private
def combine_methods
method_1
method_2
method_3
end
def this_happens?
# a condition that returns true or false here
end
end