如果你不改变所有模型的逻辑,它不是一个通用钩子,所以你不想在ActiveRecord::Base
中这样做。像这样的鸭子打字很糟糕。
这听起来像你有共同的行为,并处理这将是一个模块(或ActiveSupport::Concern
)。
实施例从here改性(假设你正在运行的Rails 3+)
module MaintainAnInvariant
# common logic goes here
extend ActiveSupport::Concern
included do
after_save :maintain_invariant_i_care_about
end
def maintain_invariant_i_care_about
do_stuff_pending_various_logic
end
end
现在每个共享此逻辑会明确包括它类,添加语义值
class OneOfTheModelsWithThisLogic < ActiveRecord::Base
include MaintainAnInvariant
end
class AnotherModelWithCommonLogic < ActiveRecord::Base
include MaintainAnInvariant
end
至于其余的答案,如何知道发生了什么变化,你正在寻找ActiveModel::Dirty方法。这些允许你检查你的型号有什么变化:
person.name = 'Bill'
person.name_changed? # => false
person.name_change # => nil
person.name = 'Bob'
person.changed # => ["name"]
person.changes # => {"name" => ["Bill", "Bob"]}
我怎样才能确定哪个型号更新? – Noah
您将代码包含在模型文件本身中,因此它将成为“that”模型,其中“that”表示模型正在更新的模型。我更新了我的示例,以清楚地说明你的'include'代码在ActiveRecord模型中 – ABMagil
如何知道'maintain_invariant_i_care_about'方法中的模型? – Noah