문제

I want to run a method that tracks changes to a records's attributes inside the CRUD, but only when they're saved with the Update action. I have this inside the model now:

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

But this runs on the creation of new records as well. Is there a test I can perform inside the check_changed method to determine whether a record was created or updated? Thanks

도움이 되었습니까?

해결책

Check out the conditional callback :if and :unless

before_save :check_changed, unless: :new_record?

Or you could use 'new_record?' in your method

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

Edit: Should also check out

after_save :check_changed, on: [:update]

Docs are here

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top