2012-01-27 47 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