So I've got a ruby on rails code which use float a lot (lots of "to_f"). It uses a database with some numbers also stored as "float" type.
I would like to migrate this code and the database to decimal only. Is it as simple as migrating the database columns to decimal (adding a decimal column, copying float column to decimal one, deleting float column, renaming decimal column to old float column name), and replacing "to_f" with "to_d" in the code? Or do I need to do more than that?
Thanks a lot everyone Raphael
You can easily use a migration to do this, and Rails will generate some of the code for you.
From your command prompt, create a new migration:
rails generate migration change_price_column_to_decimal
Rails will create the migration in the directory db/migrate
. The filename will be a timestamp followed by _change_price_column_to_decimal.rb
.
In the generated migration, you'll add up
and down
methods to convert the field:
class ChangePriceColumnToDecimal < ActiveRecord::Migration
def up
change_column :products, :price, :decimal, :precision => 15, :scale => 2, null: false
end
def down
# Either change the column back, or mark it as irreversible with:
raise ActiveRecord::IrreversibleMigration
end
end
To perform the migration, run the appropriate rake task from your command prompt:
rake db:migrate
This will convert the database for you. Keep in mind that when converting from float to decimal you will lose some significant digits, depending on what you set scale
to, though if you're dealing with prices of products, this probably isn't going to be much of an issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With