【问题标题】:Why Active Record storing integer value in the format of BigDecimal notation?为什么 Active Record 以 BigDecimal 表示法的格式存储整数值?
【发布时间】:2016-03-14 13:39:33
【问题描述】:

我是新手。观察以下屏幕截图,我有一个模型Books,带有以下列。

class CreateBooks < ActiveRecord::Migration
  def change
   create_table :books do |t|
     t.string :title
     t.text :author
     t.integer :price
     t.integer :book_id
    end
 end
end

稍后我向现有表添加一列,如下所示

class AddBookIdToBooks < ActiveRecord::Migration
  def change
    add_column :books, :book_id, :integer
  end
end

我使用form helpers 将记录添加到表Book。但它以BigDecimal 表示法而不是integer 的格式存储book_id 值。

为什么要这样存储?提前致谢。

在此处查看以下屏幕截图

2.2.2 :023 > Book.all
Book Load (0.4ms)  SELECT "books".* FROM "books"
=> #<ActiveRecord::Relation [#<Book id: 7, title: "Wings Of Fire",   author: "kalam's", price: 120, created_at: "2015-12-09 09:57:10", updated_at: "2015-12-09 09:57:10", book_id: #<BigDecimal:4f39ea0,'0.1001E4',9(27)>>]> 

【问题讨论】:

  • 您使用的是哪个 DBMS? (postgres、mysql 等)
  • sqlite db @Max Williams
  • 不回答问题,但价格不应该是浮点数而不是整数吗?如果这本书是 7.99 美元怎么办?
  • 进入该数据库的 sqllite 控制台并输入 .schema books 的结果是什么?
  • ' sqlite&gt; .schema books CREATE TABLE "books" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar, "author" text, "price" integer, "created_at " datetime NOT NULL, "updated_at" datetime NOT NULL, "book_id" integer);' @Max Williams

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

您无需为模型添加 ID。 Rails 为您完成。当您添加一个名为“model”_id 的列时,Rails 会推断它将是对其他表(关联)的引用。

【讨论】:

  • 哦,好的。谢谢您的回复。但我的问题是为什么它以“BigDecimal”格式存储“整数”值? @布鲁诺保利诺
  • 这很奇怪@NarasimhaReddy。你确定你已经用 t.integer 运行了迁移吗?因为您似乎正在使用 t.decimal 。尝试回滚您的数据库并在没有此 book_id 列的情况下再次迁移,看看会发生什么。
  • 我很高兴你解决了:D。你能发布你的解决方案@NarasimhaReddy 吗?
猜你喜欢
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-26
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 2017-01-16
相关资源
最近更新 更多