【问题标题】:Ruby on Rails Precision and Scale not behaving as expectedRuby on Rails Precision 和 Scale 未按预期运行
【发布时间】:2014-11-10 00:58:41
【问题描述】:

我正在关注《使用 Rails 4 进行敏捷 Web 开发》一书,但似乎在理解规模应该做什么或我的代码不正确方面存在问题。我将价格字段的精度设置为 8,比例设置为 2。我希望这意味着当我以某种形式添加产品时,无论我输入什么数字,它都只会显示小数点后 2 位数字。例如,输入价格为 45.12345 会在产品创建后显示为 45.12,但我看到的整体与我输入的完全一样。

这里是 schema.rb:

# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

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

  create_table "products", force: true do |t|
    t.string   "title"
    t.text     "descritpion"
    t.string   "image_url"
    t.decimal  "price",       precision: 8, scale: 2
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

【问题讨论】:

  • 您使用的是什么数据库。默认的 sqlite3?
  • 是的 sqlite3,我原以为这本书会提到这个限制,因为它建议您使用该数据库。

标签: ruby-on-rails-4 precision


【解决方案1】:

假设您使用的是默认 SQLite3 数据库,您应该会看到 this answer 关于 SQLite 中的小数。本质上,SQLite(顾名思义)不具备其他 SQL 数据库的所有功能。它会忽略精度和比例属性,只会将数字存储为real

其他答案中最相关的部分:

所以 decimal(10,5) 表示该字段应该用于存储一个 值的长度最多为 10 位,前面最多为 5 位 小数点,小数点后最多五位。

当然,输入的任何值都会被存储,即使它不保存 到这些规则,这意味着字段定义基本上是 文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多