我有類似下面的代碼:如何檢查ActiveRecord的after_save回調中是否更改了關聯的記錄數組?
class MyModel < ActiveRecord::Base
has_many :associated_records
accepts_nested_attributes_for :associated_records
after_save :send_notification, if: :relevant_data_changed?
def relevant_data_changed?
return self.some_column_changed? || self.associated_records.changed?
end
def send_notification
# Do stuff
end
end
我知道我可以檢查一列是直接在模型是否改變(如我在這個例子中所做的那樣),我想你可以同樣甚至檢查是否如果與該對象存在has_one
關係(通過self.nested_model.changed?
我相信),但單個嵌套對象已更改,但我無法弄清楚如何檢查對象數組是否已更改,例如我的示例中的associated_records
。
編輯:爲了記錄,我沒有嘗試從這裏建議的解決方案:Rails: if has_many relationship changed。但在僅僅添加或刪除對象而不是實際更改的情況下它不起作用。
有沒有人知道我可以做到這一點?謝謝。