I need to perform some atomic arithmetic in Rails but the only way I've found to do it for single objects is via the crude update_all
class method, e.g.:
Account.update_all(["debits = debits + ?", amount], :id => id)
With collection associations, the update_all
class method should be usable as an association method, since the collection will pass missing method calls on to the class with the relevant scope:
accounts.update_all(["debits = debits + ?", amount])
When dealing with collections, this is much nicer and less repetitive. However this doesn't work for singleton associations, i.e. belongs_to
and has_one
. The method_missing
for AssociationProxy
passes through to the target instance, which won't have an update_all
instance method (naturally).
Is there a more elegant way to perform this arithmetic? Or is update_all
as good as it gets?