【发布时间】:2018-04-04 10:39:50
【问题描述】:
在 Rails 应用程序中,我使用 after_update 回调,它在传递如下条件方法时运行多个方法:
app/models/my_model.rb
class MyModel < ApplicationRecord
after_update :method_1, :method_2, :method_3, if: :this_happens?
#some custom methods
private
def this_happens?
# a condition that returns true or false here
end
end
我注意到 this_happens? 方法被执行了 3 次,就在 :method_1、:method_2、:method_3 之前。
这是有道理的,因为这三个回调方法中的任何一个都可能以这样一种方式更改数据,即必须再次评估条件以确保在每种情况下都满足它。但是,当您知道这 3 种方法不会以任何可能改变条件评估的方式更改数据时,是否可以只运行一次 this_happens? 并获得一些效率?
我似乎在网上找不到任何东西,不知道是否有人可以提供建议。
PS。使用 Rails 5.1
【问题讨论】: