Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - How to migrate code from float to decimal?

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

like image 615
user1723110 Avatar asked Nov 06 '12 16:11

user1723110


1 Answers

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.

like image 173
Michael Hampton Avatar answered Nov 15 '22 03:11

Michael Hampton