Ruby on Rails - 如何将代码从浮点数迁移到十进制数? [英] Ruby on Rails - How to migrate code from float to decimal?

查看:35
本文介绍了Ruby on Rails - 如何将代码从浮点数迁移到十进制数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 ruby​​ on rails 代码,它经常使用浮点数(很多to_f").它使用一个数据库,其中一些数字也存储为浮点"类型.

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.

我只想将此代码和数据库迁移到十进制.是否像将数据库列迁移到十进制(添加十进制列,将浮点列复制到十进制一,删除浮点列,将十进制列重命名为旧的浮点列名称)并将代码中的to_f"替换为to_d"一样简单吗??或者我还需要做更多的事情吗?

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?

非常感谢大家拉斐尔

推荐答案

您可以轻松地使用迁移来执行此操作,Rails 将为您生成一些代码.

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 将在目录 db/migrate 中创建迁移.文件名将是一个时间戳,后跟 _change_price_column_to_decimal.rb.

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

在生成的迁移中,您将添加 updown 方法来转换字段:

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

要执行迁移,请从命令提示符运行适当的 rake 任务:

To perform the migration, run the appropriate rake task from your command prompt:

rake db:migrate

这将为您转换数据库.请记住,当从浮点数转换为十进制数时,您将丢失一些有效数字,具体取决于您将 scale 设置为什么,但如果您处理的是产品价格,这可能不会是一个很大的问题.

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.

这篇关于Ruby on Rails - 如何将代码从浮点数迁移到十进制数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆