2014-03-05 51 views
5

我有一個模型,它存儲零售店的詳細信息。rails after_save無限循環

在直銷模式,我過濾

after_save :is_outlet_verified 

def is_outlet_verified 
    if self.latitude.present? && self.longitude.present? 
     self.update_attributes(:is_verified => true) 
    else 
     self.update_attributes(:is_verified => false) 
    end 
    end 

我想is_verified字段設置爲true如果出口地理編碼之前有一個。但是,當is_outlet_verified成功執行時,會觸發after_save回調,這會再次觸發is_outlet_verified。

回答

16

理想情況下,你會做這樣的事情在一個before_save回調,而不是after_save - 只需設置is_verified屬性,然後只需按正常方式進行保存即可。

如果您確實需要這樣做,您可以使用update_column而不是update_attribute,它將跳過所有回調。

需要注意的一點 - 如果before_save回調返回false,則保存不會繼續。

+0

你有一個小錯字方法名稱'update_columns'爲http://apidock.com/rails/ActiveRecord/Persistence/update_columns – theDrifter

4

.update_attributes調用.save方法,所以調用它after_save創建了一個無限循環

我會做before_save,像這樣:

before_save :is_outlet_verified 

    def is_outlet_verified 
    if self.latitude.present? && self.longitude.present? 
     self.is_verified = true 
    else 
     self.is_verified = false 
    end 
    end 
+0

我嘗試過,但它不更新「is_verified」字段。 – CodeMaster123

+0

獲取任何錯誤? –

+1

不,但在更新sql查詢中,它不會更新is_verified字段。 – CodeMaster123

2

您可以使用after_create代替after_save避免infinte環路發生由update_attributes

+0

但我想執行該方法,每次我對給定的記錄進行任何更改。 – CodeMaster123

+0

然後使用'after_commit' https://github.com/rails/rails/commit/da840d13da865331297d5287391231b1ed39721b –