[英]Rails: Check which method initiated save inside :before_save
我想運行一個跟蹤CRUD內記錄屬性更改的方法,但只有當它們與Update操作一起保存時才會運行。 我現在在模型中有這個:
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方法中執行測試以確定是創建還是更新了記錄? 謝謝
檢查條件回調: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]
文件在這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.