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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…