Basically what I'm trying to do is get the sum of 2 columns and save
those results in another. I guess I'm looking to do something like
this:
a = Product.find(:all)
b = Product.sum("test + test2", :group => "id")
a.test3 = b
a.save
Obviously that doesn't work, but I'm trying to achieve something like
that. Any suggestions?
Basically what I'm trying to do is get the sum of 2 columns and save
those results in another. I guess I'm looking to do something like
this:
a = Product.find(:all)
b = Product.sum("test + test2", :group => "id")
a.test3 = b
a.save
Obviously that doesn't work, but I'm trying to achieve something like
that. Any suggestions?
Product.update "test3 = test+test2" would probably do it.
Just to give another perspective... Do you really need to save the
sum? Could it be calculated whenever you need it? If you save the sum
you need to be confident that nothing will cause your data to get out
of sync, such as some update to 'test' that does not update the sum.
If you decide you do want to save the sum, could the database
management system handle it for you? E.g. in PostgreSQL you can define
triggers - in this case a trigger could update the sum for you no
matter how 'test' and 'test2' are updated. You'd then have much
greater faith in the reliability of each sum.