Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The behavior of `attribute_changed?` inside of after callbacks will be changing

I just upgraded a project to Rails 5.1.0 and I'm seeing this deprecation warning.

DEPRECATION WARNING: The behavior of `attribute_changed?` 
inside of after callbacks will be changing in the next version of Rails.
The new return value will reflect the behavior of calling the method 
after `save` returned (e.g. the opposite of what it returns now). 
To maintain the current behavior, use `saved_change_to_attribute?` instead. 

My code looks like this

class MyClass
  before_valiadtion :my_method

  def my_method
    if name_changed?
      ...
    end
  end
end

I do not understand exactly the deprecation warning. If I use saved_change_to_name instead it will check it after it is saved but this is before validation callback.

I also noticed that if I change the name_changed? to saved_change_to_name my specs are not passing.

I'm having a hard time understanding what the appropriate way to this should be. It seems to me that how it was before it was doing the job okay, not fully understand the reason behind this change and how I should avoid these deprecation warnings.

like image 435
Martin Avatar asked May 10 '17 10:05

Martin


1 Answers

There are new names for these methods that more clearly express wether you're looking for a change that has just been saved, or one that is about to be saved.

In your case, the latter one, you're supposed to use will_save_change_to_attribute?(:name).

The deprecation warning is really misleading as it only mentions the first case, and assumes it must occur in an after callback.

like image 68
Janosch Avatar answered Oct 16 '22 10:10

Janosch