Typically, one has two options to get rails to play nicely with this:
- To add a workaround in the model to scrub out unacceptable characters.
Each of these strikes has always struck me as a bit cumbersome and intelligent. Surely this operation is common enough that a plugin of sorts must exist to handle this. …right?…….
Well I’m glad to tell you that after much searching, I’ve found a gem that does the trick. It’s called autonumeric-rails and it can be found on github or on rubygems.org. The Gem uses the autoNumeric jquery plugin to format a numerical input with commas, dollar signs or whatever else you might want.
Here’s how it works:
On top of the jquery plugin it makes the input agreeable with rails by creating a pair of inputs for each field: one visible, one invisible. The visible one is formatted using the standard jquery plugin, but the invisible one only contains the numerical value of the formatted visible field. Therefore, upon submitting a form, only the invisible, unformatted field is submitted.
So how do i use it?
Implementing the gem is very simple and it can be used with most of the options from the autoNumeric jquery plugin. Here’s how:
1. Add the plugin to your Gemfile and “bundle install”
//= require jquery
//= require autonumeric
3. Add the necessary data attribute to your input field.
This is where the autoNumeric jquery plugin site comes in handy, which has an interactive interface for building the appropriate data attribute based on your needs. Here are a couple examples.
4. That’s it, enjoy!
…But wait is it? Not quite, if you’re adding fields dynamically
Now you’re actually done. Happy coding!