will_save_change_to_attribute?(attribute) in Rails

Patrick Wendo - Oct 4 '22 - - Dev Community

Everyday I learn about new methods in rails and it absolutely floors me how awesome this framework is.

Context

Imagine you have 2 models, User and InGameTrophies. The InGameTrophies holds a lot of data about the trophy type, date of acquisition etc etc. A user can have multiple trophies. Now whenever a trophy item gets updated, we want to run a background job only if one field, say trophy type gets changed. In comes the saved_change_to_#{field_name}? and will_save_change_to_#{field_name}?

...
#if the trophy has already been saved then
SomeBackgroundJob.call() if @trophy.saved_change_to_trophy_type? 
...

#if the trophy type has not yet been saved then
SomeBackgroundJob.call() if @trophy.will_save_change_to_trophy_type? 
...
Enter fullscreen mode Exit fullscreen mode

Pretty neat, right? I think it is. more reading

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .