Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 and saving decimal values from a form

I have an odd bug in one of my applications.

When I am using the sqlite3 database the bug is not present. However when I use mysql2 as the database adapter I run into an error saving decimal values from a form.

If I submit the value 19.99 my input after the decimal is removed and it is stored in the database as 19.00

What would cause this? The database has the correct settings for the column and I can create a correct record using the rails console.

Edit: Said integer when I really wanted to say decimal.

like image 776
Devin M Avatar asked May 15 '11 04:05

Devin M


1 Answers

I think it could be one of these possibilities:

  1. A validation in your Rails model (or some step in your controller) is setting the value to an integer, or at least truncating the decimals, before saving to the database. To see if this is the case, check your INSERT operation in your logs and see what data Rails is trying to put in.

  2. If Rails is sending 19.99 instead of 19.00, you most likely have a small discrepancy between data types in your two databases. Check to see if your MySQL database is simply not storing the decimal with a scale of 2 or higher. MySQL by default stores data types with a precision of 10 and a scale of 0, thereby NOT storing decimals.

If #2 is the problem, the solution is to generate a migration and 'change' your field type to specify a scale, something like:

# 'up' portion of a new migration
def self.up
  change_column :mymodel, :myfield, :decimal, :precision => 6, :scale => 2
end
like image 125
sscirrus Avatar answered Sep 21 '22 04:09

sscirrus