Thing well made: detecting changes in Rails objects
I’m a pretty big fan of Ruby on Rails and occasionally I come across some particularly well-made parts. Rails’ ability to track changes in objects in memory has been around well over a year but its staggering how much thought goes into what people might want.
How do I check the value of an object before it was changed?
Let’s say you want to keep track of the total amount a user has across all orders. Rails has built-in not only a convenient place to update the value, but it has the previous value so you can find out the difference.
So nice!
In the example below,
- there is a field in the order table called ‘order_total’.
- order_total_change is Rails-generated array returning e.g. [20.53, 21.52] if say, the order_total had gone up by 1.99.
- order_total_changed? is also Rails-autogenerated.
class Order
...
before_update :update_total_user_spend
...
def update_total_user_spend
if order_total_changed?
previous_value, new_value = self.order_total_change
self.user.total_spend += new_value - previous_value
self.user.save
end
end
Rock on!
(yes and I do need to adjust this blog template so it has a little more room for CONTENT

