Question

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

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top