0

I'm fairly new to rails and having a problem that I'm sure is not unique, but can't seem to find an elegant solution to on my own:

I have a model with a :tax_rate decimal attribute that is used to create a total later on using some multiplication in the model.

This works just fine if the user enters the tax rate as '0.09' in the tax rate field, but obviously creates an erroniously large amount when the user enters '9'.

I'm looking to create some code that will handle a whole number being entered into my form.

My form:

  <td><%= f.input :tax_rate, label: false, input_html: { class: 'taxtarget', precision: 2 }%></td>

The calcualtions in the model:

before_save :persist_calculations

validates_presence_of :price, :units

def calculated_total
    price * units + calculated_tax
end

def calculated_tax
    if self.tax_rate.present?
        self.price * self.tax_rate
    else
        self.price
    end
end

def persist_calculations
    self.total = calculated_total
    self.tax_amount = calculated_tax
end

I would like to either handle the whole number by preventing a whole number (requiring a decimal point) or by converting a whole number into a decimal by adding two decimal places to it.

Anyone have any good resources or ideas for how to accomplish this?

PSCampbell
  • 858
  • 9
  • 27

1 Answers1

0

Either add a validation to your model for tax_rate so that it cannot be a larger than 1.0:

validates :tax_rate, less_than: 1.0

and/or add a before_validation to your model that converts large numbers to small ones:

before_validation ->(obj) {
  obj.tax_rate = obj.tax_rate / 100 if obj.tax_rate > 1
}

and/or handle it your controller, which is generally preferable to using callbacks.

Aaron Breckenridge
  • 1,723
  • 18
  • 25