Reputation: 11
I need to update any records in my database where the amount attribute is of a given value. The amount attribute is saved as a BigDecimal
.
Specifically my method to update an amount was incorrectly storing 14.97 as 149700 and 497 as 49700. So I have some correct 14.97 values and some 149700 values as well as some 497 values and 49700 values.
I need to find all records where the BigDecimal
amount attribute, when converted to a float, would be 149700 and then update these records to 14.97 but store that as a BigDecimal
and the same for 49700 to 4.97.
If the value was a float, I could just use:
Foobar.where(amount: 14.97)
But how do you find the amount where the BigDecimal(:amount).to_f == 14.97
?
Upvotes: 1
Views: 209
Reputation: 3019
You can use Enum to search for records that match the criteria. I'd go with select
:
BigDecimal
has a to_f
method so you can do something like:
users_to_update = User.all.select { |user| user.amount.is_a?(BigDecimal) && user.amount.to_f == 14.97 }
then there is a to_d
method for Float
so you can do:
users_to_update.each { |user| user.update_attributes(amount: 14.97.to_d) }
Upvotes: 1