2017-05-08 32 views
-3

我試圖每次創建記錄和更新記錄後調用一個函數使用回調,我應該使用哪個回調函數,以便它不會給我堆棧級別深錯誤 我的模型代碼堆棧級別深入rails回調函數

class T < ApplicationRecord 

    before_commit :calculate 
    before_update :calculate 

    def calculate 
    t = get_w + get_t + get_a 
    self.amount = t 
    self.save! 

    end 

    def get_w 
    end 

    def get_a 
    end 

    def get_t 
    end 

end 
+0

[\ _Update方法後,Rails堆棧級別太深隨着]的可能的複製(http://stackoverflow.com/questions/43797001/ Rails的堆棧層次太深有-後更新方法) –

回答

3

至少你的回調的一個被再次調用(因此,遞歸),當你調用save!方法。試試刪除那一行。

1

你遇到的問題是你有一個'before_update',然後你調用保存觸發前更新。那就是再次調用同樣的方法

1

試試下面的代碼:

class T < ApplicationRecord 

    before_commit :calculate 
    before_update :calculate 
    def calculate 
    t = get_w + get_t + get_a 
    self.amount = t 
    #self.save! comment this line, because it call `before_commit` callback again and again 

    end 

    def get_w 
    end 

    def get_a 
    end 

    def get_t 
    end 

end 
相關問題