Reputation: 23
in my application lots of objects are already preloaded by Rails.
Now I like to update some of these object attributes. Unfortunately some of these objects are related to the same object in my database. When I add a value to myObject.balance (myObject.balance += value
), the attribute balance in differentButSameObject has still the same value.
One solution could be reloading the object. I would prefer to update the value like this:
UPDATE myTable SET balance = balance + 10 WHERE id = 1
.
Is this possible?
Upvotes: 2
Views: 1754
Reputation: 13058
You can add the following code to your model. It uses the update_counters which performs a proper query (that does COALESCE, for instance):
def inc(counter, by = 1)
raise "Cannot update column of a non-persisted model" unless persisted?
self.class.update_counters(id, counter => by)
increment(counter, by)
end
Upvotes: 0
Reputation: 1171
You could use ActiveRecords update_all statement:
Object.where(:id => 1).update_all("balance = balance + 1")
Upvotes: 6