我想运行一个跟踪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方法中执行测试以确定是创建还是更新了记录?感谢
答案 0 :(得分:2)
检查条件回调:if和:unless
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