2012-01-27 52 views
14

它看起來像Paperclip不尊重ActiveRecord髒模型。如何檢測after_save回調中的更改。如何在after_save回調中檢測回形針附件是否已更改?

class User 

    has_attachment :avatar  
    after_save :do_something 

    def do_something 
    if name_changed? 
     # 
    end 

    # How to determine avatar was changed? 
    #if avatar_changed? 
    # # 
    #end 

    end 
end 

注意

我知道我可以檢測使用avatar.dirty?電話before_save回調的變化,但dirty標誌被設置爲false後保存。

我可以添加一個處理器,但是我需要在模型數據保存後執行我的操作。

回答

26

你可以嘗試訪問_changed?方法中的一個屬性:

if avatar_updated_at_changed? 
    # do something 
end 
+1

這是我我現在正在做。我想知道是否有更好的方法。 – 2012-01-27 06:00:16

+1

你有沒有想出更好的解決方案? – 2015-03-30 17:19:22

3

當我需要訪問這些數據保存後,我通常採取這種做法:

class Foo 

    has_attachment :avatar 
    before_save :check_for_avatar_changes 
    after_save :do_something 

    def do_something 
    if @avatar_has_changes 
     # 
    end 
    end 

    def check_for_avatar_changes 
    @avatar_has_changes = self.avatar.dirty? 
    end 

end 
+0

爲了提高你的文章的質量,請包括你的文章如何/爲什麼會解決問題。 – 2012-10-06 06:48:47

+0

check_for_avatar_changes的代碼有問題...如果函數返回false,模型將不會被保存,因爲它是before_save回調。 – Christian 2016-09-21 14:50:56