Rails序列化将0转换为String

时间:2013-05-20 17:45:53

标签: ruby-on-rails serialization

我有一个使用默认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转换为String表示某些比较失败。我可以用to_i映射数组,但我很好奇为什么会发生这种情况。我正在使用Rails 3.2.13和Ruby 1.9.3

2 个答案:

答案 0 :(得分: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上的一个示例应用程序有这个错误/错误/行为?

答案 1 :(得分:0)

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