Assume there is a table named somethings
with a column value
of type float
.
The schema is shown below.
# == Schema Information
#
# Table name: somethings
#
# id :bigint not null, primary key
# value :float not null
# created_at :datetime not null
# updated_at :datetime not null
Then, "update the value of all records in the somethings table to 0.4, then subtract 0.1".
The code is shown below.
Something.update_all("value = 0.4")
Something.update_all("value = value - 0.1")
After this operation, the value columns of the records in the somethings table are all 0.3000000000000000000000004
, resulting in a rounding error.
I want to update without rounding errors, but how can I do it?
Note that I am aware that if I write the following without update_all
, there will be no rounding error.
Something.update_all("value = 0.4")
Something.find_each do |s|
s.update(value: (s.value.rationalize - 0.1.rationalize).to_f)
end
However, I would like to use update_all
as much as possible for faster updates, as performance is severely degraded when the somethings
table has a large number of records.