2

我有一个模型,它使用默认的 Rails 序列化来序列化数组。看哪:

class Account < ActiveRecord::Base
  serialize :number_of_free_jobs
end

number_of_free_jobs是一个 FixNums 数组,但出于某种原因,Rails 会将所有为 0 的条目转换为字符串,但将其余条目保留为 FixNums,请检查它:

account = Account.last
account.number_of_free_jobs = [10, 5, 0, 1]
account.save
account.number_of_free_jobs 
=> [10, 5, "0", 1]

将 0 转换为字符串意味着某些比较失败。我可以映射数组,to_i但我很好奇为什么会这样。我正在使用 Rails 3.2.13 和 Ruby 1.9.3

4

2 回答 2

1

这不会发生在我的机器上(Sqlite3、Rails 3.2.13 和 Ruby 1.9.3):

Loading development environment (Rails 3.2.13)
irb(main):001:0> Account
=> Account(id: integer, number_of_free_jobs: string, created_at: datetime, updated_at: datetime)
irb(main):002:0> Account.create
   (0.1ms)  begin transaction
  SQL (9.5ms)  INSERT INTO "accounts" ("created_at", "number_of_free_jobs", "updated_at") VALUES (?, ?, ?)  [["created_at", Mon, 20 May 2013 18:19:26 UTC +00:00], ["number_of_free_jobs", nil], ["updated_at", Mon, 20 May 2013 18:19:26 UTC +00:00]]
   (179.1ms)  commit transaction
=> #<Account id: 2, number_of_free_jobs: nil, created_at: "2013-05-20 18:19:26", updated_at: "2013-05-20 18:19:26">
irb(main):003:0> account = Account.last
  Account Load (0.3ms)  SELECT "accounts".* FROM "accounts" ORDER BY "accounts"."id" DESC LIMIT 1
=> #<Account id: 2, number_of_free_jobs: nil, created_at: "2013-05-20 18:19:26", updated_at: "2013-05-20 18:19:26">
irb(main):004:0> account.number_of_free_jobs = [10, 5, 0, 1]
=> [10, 5, 0, 1]
irb(main):005:0> account.save
   (0.1ms)  begin transaction
   (0.4ms)  UPDATE "accounts" SET "number_of_free_jobs" = '---
- 10
- 5
- 0
- 1
', "updated_at" = '2013-05-20 18:19:46.430558' WHERE "accounts"."id" = 2
   (155.9ms)  commit transaction
=> true
irb(main):006:0> account.number_of_free_jobs 
=> [10, 5, 0, 1]

您能否提供重现此问题的步骤?也许 github 上的示例应用程序具有此错误/错误/行为?

于 2013-05-20T18:27:47.373 回答
0

问题在于Tolk gem 安装safe_yaml作为依赖项。删除 Tolk 删除了依赖项,并且不再将零转换为字符串。有点奇怪,我会研究为什么 safe_yaml 会这样做......

于 2013-05-21T10:17:25.740 回答