Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get changed attributes on after_update callback

I'm trying to make a conditional after_update, I have the following:

  after_update do |participant|
    Rails.logger.info "#{self.previous_changes} changed."
    if self.previous_changes.include?(:current_distance)
      #Do my stuff ...
    end
  end

The logger prints empty hash: {}

How can I check which attribute has been changed?

I am using: participant.update_attribute(:current_distance, distance) to update the attribute.

like image 479
Danpe Avatar asked Apr 06 '14 16:04

Danpe


1 Answers

You want to use changes not previous_changes. You are still in the same save transaction so what you are looking for is in changes. The previous_changes won't have the information until after the update completes.

RAILS 5.1.1:
use saved_changes instead of changes as it will be deprecated in new versions.

like image 104
Alex Peachey Avatar answered Oct 19 '22 20:10

Alex Peachey