2014-01-23 84 views
0

我想要運行一種方法來跟蹤CRUD中記錄屬性的更改,但只有當它們使用Update操作保存時。我現在在模型裏面有這個:Rails:檢查哪個方法啓動保存在裏面:before_save

before_save :check_changed 
def check_changed 
    puts "Period Contributions Changed? : #{period_contributions_changed?}" 
    puts "Total Contributions Changed? : #{total_contributions_changed?}" 
    puts "Period Expenditures Changed? : #{period_expenditures_changed?}" 
    puts "Total Expenditures Changed? : #{total_expenditures_changed?}" 
end 

但是這也在創建新記錄時運行。有沒有可以在check_changed方法內執行的測試來確定是否創建或更新記錄?由於

回答

2

退房條件回調:if和:除非

before_save :check_changed, unless: :new_record? 

或者你可以使用「new_record?在你的方法

def check_changed 

    return if new_record? 

    puts "Period Contributions Changed? : #{period_contributions_changed?}" 
    puts "Total Contributions Changed? : #{total_contributions_changed?}" 
    puts "Period Expenditures Changed? : #{period_expenditures_changed?}" 
    puts "Total Expenditures Changed? : #{total_expenditures_changed?}" 
end 

編輯:還應該檢查出

after_save :check_changed, on: [:update] 

文檔是here