My form has the following:
<%= f.select(:amount, Order::AMOUNT_VALUES, {:blank => false}) %>
My model has:
AMOUNT_VALUES = { '$ 0.50' => 0.5, '$ 1' => 1, '$ 2' => 2, '$ 5' => 5, '$ 10' => 10 }
validate :amount_values_to_be_of_certain_values
def amount_values_to_be_of_certain_values
puts self.amount
unless AMOUNT_VALUES.has_value? self.amount
errors.add(:amount, 'not a valid field')
end
end
If I select 0.5 and submit the form. The form complains saying “Amount not a valid field”. If I select one of the other values, the form submits fine.
It seems the problem is with a decimal point that starts with 0.
What is wrong here?
If you’re storing amount in an integer field, then it’s going to round any floating point numbers you put into it down. That’s why self.amount.to_f is 0.0, because putting 0.5 into an integer field changes it to 0, and 0.to_f is 0.0.