How to disable dollar signs from value to check in Rails?

Here is what I use in my model:

before_validation :strip_dollar_sign

validates :amount_due,
          :format => { :with => /^\d+??(?:\.\d{0,2})?$/ }, 
          :numericality => {:greater_than => 0}

private

def strip_dollar_sign
  self.amount_due = self.amount_due.to_s.tr!('$,','').to_f
end

If I run the line from the strip_dollar_sign function manually in the Rails Console, I get exactly what I want (i.e. $ 400 ends as 400.0), but when I use the actual form in my application, the value always ends as 0.0. Anyone get what I'm doing wrong?

+7
source share
3 answers

Three issues here:

  • As Stefan pointed out in his answer , you can delete ,in your call tr!, although this will not affect the replacement $.

  • tr! . tr! ( Ruby !) nil, . nil.to_f - 0.0, (, , , . ). tr.

  • Rails , , , "$400".to_f 0.0, , . , amount_due= :

    def amount_due=(value)
      value = value.to_s.tr('$', '').to_f
      write_attribute(:amount_due, value)
    end
    
+17

$, $, $.

+3

I recommend doing this in javascript. Rails seems to do some magic with form helpers, which convert any non-numeric value into a field that is supported by a digital database type of up to 0.0. Stupid, I know.

-2
source

All Articles