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.
I think it could be one of these possibilities:
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.
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
Related
I'm implementing the tutorial http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/accessing-your-model's-data-from-a-controller
I use Entity Framework 4.1. In the database decimal value is mapped (18,2).
In the creating form I entered 1000 but in the details page the decimal value output is 1000,00 and also in the edit page as well.
I use #Html.EditorFor(model => model.Price) for input and for output.
When I looked at the database created by the Entity Framework the Price column which is my decimal value is created with this SQL command:
[Price] DECIMAL(18,2) NOT NULL
Why there is inconsistance?
You are comparing two different things. The mapping describes the precision which can be stored in the database but it has nothing to do with the way how your ASP.NET MVC View shows decimal number - it is handled by output formatting.
I'm facing a problem with Rails application to store decimals in my mysql database. I have a form with two fields: "amount" and "currency". When I enter a decimal value in the "amount" field (for example 1,22) Rails just stores the 1 in the database.
My log file looks like this:
Started POST "/cashamounts" for 127.0.0.1 at 2012-02-04 13:23:54 +0100
Processing by CashamountsController#create as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"QpWGfEtDR1tc7wTFmZZst9gYjKAyXtRypilsxDE9Tzs=", "cashamount"=>{"currency_id"=>"eur", "amount"=>"1,22"}, "commit"=>"Create Cashamount"}
[1m[36mCurrency Load (2.8ms)[0m [1mSELECT `currencies`.* FROM `currencies` ORDER BY name[0m
[1m[35m (0.2ms)[0m BEGIN
[1m[36mSQL (0.3ms)[0m [1mINSERT INTO `cashamounts` (`amount`, `created_at`, `currency_id`, `updated_at`) VALUES (1, '2012-02-04 12:23:54', 'eur', '2012-02-04 12:23:54')[0m
[1m[35m (0.6ms)[0m COMMIT
Redirected to http://localhost:3000/cashamounts/8
Completed 302 Found in 94ms
So the amount is stored in the params correctly, but is not inserted correctly into the database. I checked my db/schema.rb file. The line for the column "amount" is:
t.decimal "amount", :precision => 10, :scale => 2
Where else can I look to find the problem?
PS. I started off with using the money gem, but that showed the same problem: all digits after the "," are not stored.
This question is a bit old, but for future visitors I believe the answer can be found in the "Gotcha" section of:
http://torontoprogrammer.ca/2010/05/decimal-numbers-in-rails-and-mysql/.
Basically, when you set up the decimal field you have to specify the scale argument to say how many places should be to the right of the decimal point. Otherwise, mysql assumes that you want all of your digits to the left of the decimal point.
This problem bit me too. Everything worked fine in my dev environment (using sqlite), but in production (using mysql), the fractional part of my "decimal" numbers was getting truncated.
1,22 is the European notation for decimal values, while 1.22 is the British, American and Australian convention. You may need to set your locale.
http://guides.rubyonrails.org/i18n.html#optional-custom-i18n-configuration-setup
In an initializer:
I18n.default_locale = :fr
Or at the end of config/application.rb
config.i18n.default_locale = :fr
The problem is that Rails expects a decimal point and not a comma. If this is user input try substituting the , for . before saving to the database.
Rails' :timestamp column type lies; it's actually just an alias for :datetime.
I'm using mysql, and I want to use actual unix-timestamp TIMESTAMP columns.
a) Is there a nice way to set this, other than just making the column using SQL?
b) Will ActiveRecord cope with it properly (e.g. converting to Time when necessary, accepting a unix timestamp Integer as input, etc)? What gotchas should I expect to have to handle, and where?
Why:
Speed. This is for an extremely active table that's aggregating outside data sources that already use unix timestamps. Converting to datetime (or even converting first to a db string, which goes through 2 gsubs) uses up the majority of its import time. I could otherwise be doing just a dirt cheap Integer#to_s call.
Timezones. I don't want 'em. I want it stored timezone-agnostically; dealing with timezones is a pain and is completely irrelevant to my needs except at the very final stage before individual user display. The data itself has no need to know what timezone it was recorded in.
Size. It's a large table. TIMESTAMP is half the size of DATETIME.
Yes, I would still be doing updated_at calculations in code, not mysql. That part isn't a bottleneck.
Why your 'why not' is wrong (preëmptively, to show I'm not asking for noobish reasons :-P):
"But TIMESTAMP auto updates": That's only true by default, and can be easily switched off.
I'm actually not using Rails, just ActiveRecord.
Yes, this is based on actual profiling data; I am not early optimizing. ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter#quote (in Quoting#quoted_date [if passing Time] or Mysql2Adapter#quote_string [if preconverting to_s(:db)]) is actually the most CPU-consuming section of my scraper. I want rid of it.
this works (just added whitespace character to type definition, so :timestamp doesn't override it):
t.add_column :sometable, :created_at, 'timestamp '
I'm pretty noobish, but I'll give it a shot. What if you were to add your own custom column, or overwrite the default ones? You can use custom data types with a string like so:
t.add_column :mysql_timestamp, 'timestamp'
and then somewhere else in your logic
def mysql_timestamp
Time.now.strftime("%Y-%m-%d %H:%M:%S")
end
Not sure about b). Only one way to find out!
I want to store mysql regular epxression to mysql database field. Specifically I want to store word boundaries expression into the database. For example:
[[:<:]]my expression here[[:>:]]
If I put this value directly into the database (for example using Sequel Pro) the value is stored correctly.
Problem occur when I want to store this value through Ruby on Rails:
my_instance.sql_expression = "[[:<:]]my expression here[[:>:]]"
my_instance.save
=> true
But value that is actually stored to database looks like this:
my_instance.sql_expression
=> "[[::]]"
It seems that in string Rails ignore everything what is between "<" and ">" including signs itselfs.
The project is in Ruby 1.8.7 and Rails 2.3.5.
This sounds like you're using something like xss_terminate to filter your models before saving them. I'd look in your model definition for something which has a before_save or other hook that might be intrusively doing this.
This is not standard Rails behavior.
exist any way to store in database a numbers with or without decimal point? The user can store to database numbers like 10 and 10.1 - for storing numbers in MySQL I use data type column decimal, so for this example, in the database will be stored 10.00 and 10.10.
But I will need to store the exact form of number by user - so in this case 0 10 and 10.1.
Is possible to solve it on database level or I have to edit on application level?
make use on case
case format(#number,0)=#number
when 1 then format(#number,0)
else
case format(#number,1)=#number
when 1 then format(#number,1)
else #number
end
end
or if
if (format(#number,0)=#number, format(#number,0),
if (format(#number,1)=#number, format(#number,1), #number))
one way is when you make the select query to omit this leading zero
http://www.foscode.com/remove-trailing-zeros-mysql-decimal-fields/
You could just save whatever the user entered as a VARCHAR, so you'll store exactly what they entered. Then when you need it, you can load it from the DB, and parse it to the corresponding float value as needed.