Danpe
Danpe

Reputation: 19047

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.

Upvotes: 12

Views: 6262

Answers (1)

Alex Peachey
Alex Peachey

Reputation: 4676

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.

Upvotes: 20

Related Questions