1

I have a good deal of forms with numerical fields that are used to enter rather large numbers. I was using some javascript to automatically place a comma to delimit the number to make it easier to read in the form. The problem is that, when the field is saved to the database, the comma in the text field makes it a non-integer, so it only saves the first set of digits (left to right) before it runs into a comma.

My question is: What is the best way to handle this? I figure it must be a relatively common situation, though I can't really find a simple answer.

I've tried adding a before validation method to strip out the commas, but at that point, the number has been altered. If I get desperate, I figure I could:

1) Add a dummy field into my view and hide the integer field

or

2) Grab and alter the parameters in my controller

or

3) Override the submit button to run a comma-clensing script prior to submit.

But all of those seem excessive. Any better practices out there for this?

Thanks in advance.

neanderslob
  • 2,633
  • 6
  • 40
  • 82

3 Answers3

1

FINALLY stumbled across the answer. There's a fantastic jquery plugin called autonumeric that formats the appearance of the textbox but not its value attribute. It even comes in a well maintained rails gem that's STOOPID-easy to use and pretty well documented. Check it out!

PS, it does not play well with simple form's f.input. You can still use simple form but on any fields you want to format, use f.text_field instead.

neanderslob
  • 2,633
  • 6
  • 40
  • 82
0

You probably need to leave the number as an integer in the database, but just display it with commas. please see this link How to print a number with commas as thousands separators in JavaScript

Community
  • 1
  • 1
Louise
  • 382
  • 1
  • 6
  • 16
0

How about allowing the fields to be string fields and then tagging on the .to_i method.

EDIT

actually you'll need to create a method for handling these input fields and call it before_save or something

inputname do |i| 
    i.delete!(',').to_i
end
RuNpiXelruN
  • 1,850
  • 2
  • 17
  • 23
  • Unfortunately, it seems that once it gets to the model, the number has been modified so that it's not useful. Even the `before_validation` happens too late. – neanderslob Jan 19 '16 at 23:11