In my Rails app, I want users to be able to input percentage values as decimals from 0.0 to 100.0. In the database, I want to store them as decimals from 0.00 to 1.00, so that calculations are easier.
I'm currently doing this through getters and setters in the model. But then, when I write derived attributes in the model, they end up using the 0-100 values instead of 0-1, which defeats the purpose of storing it in 0-1 values for easy calculation:
# in the model `quote.rb`
def discount=(value)
write_attribute :discount, value.to_f / 100
end
def discount
read_attribute(:discount).to_f * 100
end
def final_price
price * (1 - discount)
# this generates a wrong value,
# because if the user inputs discount as 50 to represent 50%,
# the final price will be `price * -49`
end
Any ideas on better ways to achieve this?
I would use a decimal column (to avoid the issues with floats and rounding) to store the raw values (as a percentage) and avoid casting.
You can then simply calculate the net price by using:
def final_price
price * (discount || 100 * 0.01)
end
When it comes to dealing with presenting the output to the user you way want to look at the money gem as it makes it easier to deal with locales and multiple currencies.