2014-09-22 49 views
0

我有一個叫做點的模型,我有2列名爲clicked_at和opened_at。創建記錄時不會輸入這兩列。這兩列將手動更新。現在我只想調用一個回調來更新clicked_at列。有沒有辦法做到這一點?幫助將不勝感激。如何針對特定列更新調用after_update回調?

回答

1

您必須手動檢查。

def my_callback 
    if clicked_at_changed? 
    clicked_at_did_change 
    end 
end 

def clicked_at_did_change 
    # do stuff 
end 
+0

它不能正常工作。它不會進入方法本身。 – 2014-09-22 10:29:18

+0

你能詳細點嗎?你嘗試了什麼,什麼不起作用? – Jesper 2014-09-22 13:42:28

0

這個.. observers將是一個不錯的選擇,有很多的選擇,當你想打電話給你的code..while更新/創建/刪除/編輯/保存......如此下去。

class PointObserver < ActiveRecord::Observer 

##this method will be called everytime AFTER you update point object 
    def after_update(point) 
    point.clicked_at =Time.now 
    point.opened_at =Time.now 
    point.save! 

    end 

end 

啓用該觀察員application.rb中

# Activate observers that should always be running. 
    config.active_record.observers = :point_observer 

你可以做任何你想要的,你也有很多回調,如before_save,before_update..etc。 此外,你可以把所有的觀察者放在app/observers/ ..