I’m using the default JSON serialization for a model that has a number of decimal and integer attributes. An example result is:
{ "user": { "id": 1234, "rating": "98.7" } }
Notice the addition of quotes around the value of “rating”. This causes the deserialization library I’m using to incorrectly treat these as strings (instead of decimals). Can Rails be set to not use the quotes for all decimals?
Edit:
I’m on Rails 3.0.7 and Ruby 1.9.2 if that makes a difference.
Edit:
Terminal:
rails g model user rating:decimal
rake db:migrate
Console:
user = User.create(rating: 98.7)
user.to_json
The only “safe” way to hand decimals from language A to language B is to use a String. If your json contains
"rating": 98.79999999999999it will probably be converted to98.79999999999998by your JavaScript runtime.See BigDecimal as_json documentation:
If you want to force Rails not to quote these, you could monkey-patch BigDecimal (see Rails source).