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

So, I have a ruby ​​on rails code that uses float a lot (a lot of "to_f"). It uses a database with some numbers, which are also stored as a type of "float".

I would like to transfer this code and database only to decimal. Is it as simple as moving the database columns to decimal (adding a decimal column, copying a float column to a decimal, deleting a float column, renaming the decimal column to the old float column name) and replacing β€œto_f” with β€œto_d” in the code? Or do I need to do more?

Thanks to all Raphael

+4
source share
1 answer

You can easily use migration to do this, and Rails will generate some code for you.

At the command line, create a new migration:

rails generate migration change_price_column_to_decimal 

Rails will create a migration in the db/migrate directory. The file name will be the timestamp followed by _change_price_column_to_decimal.rb .

In the generated migration, you add the 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 migrate, run the appropriate rake command from the command line:

 rake db:migrate 

This will transform the database for you. Keep in mind that when converting from a floating point to a decimal string, you will lose a few significant digits, depending on what you set to scale , although if you are dealing with product prices, this will probably not be a big problem.

+17
source

Source: https://habr.com/ru/post/1444407/


All Articles