Rails 4 after_save previous_changes not working

I have an after_save callback for the model, and I call previous_changes to see if the attribute (is_complete) has changed. Even when the attribute changes, previous_changes returns an empty hash.

Here's the callback:

after_save do |record|
  puts "********************"
  puts record.previous_changes.to_s
  puts record.is_complete
  puts "********************"
end

and here is what I get in the log:

********************
{}
true
********************
********************
{}
false
********************

If the value of is_complete is changed from true to false, it must be in the hash of previous_changes. Updating is done using normal save! and I do not reload the object.

--- UPDATE ---

I did not consider this when I asked the question, but my model uses the awesome_nested_set gem, and it seems like it is reloading the object or somehow interfering with the after_save callback. When I comment on act_as_nested_set, the callback works fine.

--- 2 ---

round_save, , , , , , . :

around_save do |record, block|
  is_complete_changed = true if record.is_complete_changed?
  block.call
  if is_complete_changed
    ** do stuff **
  end
end
+4
2

ActiveModel:: Dirty

274

 def changes_applied # :doc:
    @previously_changed = changes
    @changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
 end

, @previously_changed changes_applied, changes_apply save, AFTER DOING PERSISTENT WORK ( 42)

, previous_changes , (DB)

, record.changed_attributes previously_changed, !

+5

, ActiveModel::Dirty , previous_changes:

def previous_changes
  @previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new
end

@previously_changed ( , changes, ), ( , : D) .

, changes:

def changes
  ActiveSupport::HashWithIndifferentAccess[changed.map { |attr| [attr, attribute_change(attr)] }]
end

#=> {"is_complete"=>[true, false]}
+2

Source: https://habr.com/ru/post/1626921/


All Articles