如何让Rails接受小数?

时间:2017-10-06 19:39:32

标签: ruby-on-rails ruby

我在Rails-React应用程序中创建了一些表数据。

我在控制台中创建了这段数据:

2.3.3 :024 > Crop.create date: Date.today, cropname: 'Radishes', ismetric: false, bagspackaged: '20', unitweight: '0.5', totalweight: '10'

今天我意识到Rails不接受单位重量的0.5十进制,无论我如何尝试在控制台中更新它,它都不会保存。

这是我的schema.rb文件:

ActiveRecord::Schema.define(version: 20171004224716) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "crops", force: :cascade do |t|
    t.date "date"
    t.string "cropname"
    t.boolean "ismetric"
    t.integer "bagspackaged"
    t.integer "unitweight"
    t.integer "totalweight"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

4 个答案:

答案 0 :(得分:3)

这里有两个问题

  • 首先,您已将数据类型integer提供给unitweighttotalweight,而您应该按顺序提供decimalfloat接受和存储分数。具有精确度的decimal数据类型更好,因为它可以为您提供更准确的结果,如下面评论中所述'部分。 当你使用decimal时,你可以通过精确度来控制它,它是一个数字中的总位数,而scale是小数点后面的位数。

    这是一个例子

    add_column :tickets, :price, :decimal, precision: 5, scale: 2

    这将允许您存储十进制数字,如60.00,80.99和100.00

  • 其次,您将string传递给integer,这不是问题,因为只要它是有效的integer,rails就会将其转换为integer否则它将是0。但一般来说这不是一个好习惯。

答案 1 :(得分:1)

这不是小数,它是一个字符串。不要在数字文字周围加上引号。

Crop.create(
  date: Date.today,
  cropname: 'Radishes',
  ismetric: false,
  bagspackaged: 20,
  unitweight: 0.5,
  totalweight: 10
)

答案 2 :(得分:1)

您可以使用decimal(或float)类型字段而不是整数:

create_table "crops", force: :cascade do |t|
    t.decimal "unitweight"
end

然后不要在值周围使用引号:

2.3.3 :024 > Crop.create date: Date.today, cropname: 'Radishes', ismetric: false, bagspackaged: '20', unitweight: 0.5, totalweight: '10'

答案 3 :(得分:1)

我会避免回滚你的庄稼表,这只会是更多的工作。这取决于你。

我会这样做:

rails g migration ChangeUnitweightToFloat

在该文件中我会这样配置:

class ChangeUnitweightToFloat < ActiveRecord::Migration
  def change
    change_column :crops, :unitweight, :float
  end
end

通过这两个步骤,你应该去。 为了将来参考,请记住,如果你想使用小数,它将是t.decimal或t.float。

相关问题