2015-08-28 17 views
0

我有類似下面的代碼:如何檢查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。但在僅僅添加或刪除對象而不是實際更改的情況下它不起作用。

有沒有人知道我可以做到這一點?謝謝。

回答

0

那麼多挖掘一下後,事實證明,做什麼,我試圖做正確的方法是用after_addafter_remove回調。

How can I validate that has_many relations are not changed

在我的例子,這將是這樣的:

has_many :associated_records, after_add: :send_notification 

# This gets called for every new record added, even if multiple are 
# added at once 
def send_notification(new_record) 
    # Do stuff with the new_record 
end 
0

像這樣的東西應該工作:

class MyModel < ActiveRecord::Base 
    has_many :associated_records, after_save :force_save_associated_records  

    def force_save_associated_records 
    associated_records.map{|x| x.save! if x.changed?} 
    end 
end 
相關問題