DEV Community

Patrick Wendo
Patrick Wendo

Posted on

2

will_save_change_to_attribute?(attribute) in Rails

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️