【发布时间】:2012-11-27 12:28:36
【问题描述】:
我在 Postgresql 中有一个名为monthly_trips 的表。有一行值 id = 3 & al = 107.415。我的问题是当我尝试访问 rails 中“al”列的值时。使用带有以下代码的 Rails 控制台,我得到 6154.426156397738 的结果。我不知道是什么产生了这个更大的数字(准确地说是 57.295779513 倍)。任何帮助将不胜感激!如果您需要更多信息,请告诉我。
trip = MonthlyTrip.find(3)
result = trip.al
monthly_trip.rb
class MonthlyTrip < ActiveRecord::Base
attr_accessible :al, :month, :vehicle_id, :year
belongs_to :vehicle
end
psql 输出(select id, al frommonthly_trips where id = 3;)
id | al
----+---------
3 | 107.415
(1 row)
psql 输出(\d 每月一次)
Table "public.monthly_trips"
Column | Type | Modifiers
------------+-----------------------------+------------------------------------------------------------
id | integer | not null default nextval('monthly_trips_id_seq'::regclass)
vehicle_id | integer |
year | integer |
month | integer |
al | numeric(9,3) |
ak | numeric(9,3) |
az | numeric(9,3) |
ar | numeric(9,3) |
ca | numeric(9,3) |
co | numeric(9,3) |
ct | numeric(9,3) |
de | numeric(9,3) |
fl | numeric(9,3) |
ga | numeric(9,3) |
hi | numeric(9,3) |
ida | numeric(9,3) |
il | numeric(9,3) |
ind | numeric(9,3) |
ia | numeric(9,3) |
ks | numeric(9,3) |
ky | numeric(9,3) |
la | numeric(9,3) |
me | numeric(9,3) |
md | numeric(9,3) |
ma | numeric(9,3) |
mi | numeric(9,3) |
mn | numeric(9,3) |
ms | numeric(9,3) |
mo | numeric(9,3) |
mt | numeric(9,3) |
ne | numeric(9,3) |
nv | numeric(9,3) |
nh | numeric(9,3) |
nj | numeric(9,3) |
nm | numeric(9,3) |
ny | numeric(9,3) |
nc | numeric(9,3) |
nd | numeric(9,3) |
oh | numeric(9,3) |
ok | numeric(9,3) |
ore | numeric(9,3) |
pa | numeric(9,3) |
ri | numeric(9,3) |
sc | numeric(9,3) |
sd | numeric(9,3) |
tn | numeric(9,3) |
tx | numeric(9,3) |
ut | numeric(9,3) |
vt | numeric(9,3) |
va | numeric(9,3) |
wa | numeric(9,3) |
wv | numeric(9,3) |
wi | numeric(9,3) |
wy | numeric(9,3) |
created_at | timestamp without time zone | not null
updated_at | timestamp without time zone | not null
Indexes:
"monthly_trips_pkey" PRIMARY KEY, btree (id)
迁移文件
class CreateMonthlyTrips < ActiveRecord::Migration
def change
create_table :monthly_trips do |t|
t.integer :vehicle_id
t.integer :year
t.integer :month
t.decimal :al, precision: 9, scale: 3
t.timestamps
end
end
end
pg_locks 表
locktype | database | relation | virtualxid | virtualtransaction | pid | mode | granted
"relation" | 11955 | 11000 | blank | "8/18417" | 25475 | "AccessShareLock" | TRUE
"virtualxid" | blank | blank | "8/18417" | "8/18417" | 25475 | ExclusiveLock" | TRUE
【问题讨论】:
-
您在迁移中声明了
al的哪种类型? -
@cdesrosiers al 在我的迁移中被声明为精度为 9、比例为 3 的小数。这在 Postgresql 中转换为数字(9,3)。
-
当您在控制台中读取
trip.al时,您应该得到一个BigDecimal对象(#<BigDecimal: ... >)。那看起来像什么? -
您使用的是哪个版本的 Rails 和
pg?我检查了一个 3.2 应用程序,该应用程序在数据库中有一个numeric(AKA:decimal) 列,它作为 BigDecimal 被拉出。由于某种原因,您收到了Float,这是不对的。 -
@muistooshort 我在该 ruby 文件中的 Float 上尝试了 to_d 转换,并且在将其插入 PG 之前生成了相同的错误数字。 Rails 使用 Ruby 的 to_d 转换 Float 一定是有问题。感谢您向我指出这一点!
标签: ruby-on-rails postgresql activerecord rails-console