如果你不改變所有模型的邏輯,它不是一個通用鉤子,所以你不想在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