【问题标题】:simulate timestamp in seeds.rb在seeds.rb中模拟时间戳
【发布时间】:2012-03-27 18:13:48
【问题描述】:

我想通过样本数据填充数据库,出于某种原因,我还想模拟created_at。 这是我的seeds.rb:

9.downto(1) do |i|
  product = Product.new(price: 99.99)
  product.created_at = i.days.ago,
  product.save!
end

在数据库中,rake db:seed 的结果是这样的,

---- 2012-03-03 16:50:30.316886000 Z- 1

当我需要时

2012-03-03 16:50:30.316886000 Z- 1

如何避免结果中出现这些---- 符号?

(数据库:sqlite3)

更新: 我刚刚发现当我使用product.created_at = i.days.ago时, 在回调中 (before_save) created_atArray: [date_value, 1]。所以我可以使用

before_save { self.created_at = self.created_at[0] }

然后,数据库中的值将是正确的(没有----),但使用回调似乎不是一个好方法。

【问题讨论】:

  • product.created_at = (Date.new - i) 适合你吗?
  • 感谢您的建议,但不,它不起作用。我得到了一些奇怪的值 (--- -4713-12-25- 1)

标签: ruby-on-rails ruby sqlite


【解决方案1】:

问题出在这一行:

product.created_at = i.days.ago,

你需要去掉结尾的逗号,这就是为什么你会得到一个created_at 的数组。修复它,您就可以摆脱before_save 回调。

编辑:您在其中获得--- 的原因是因为您使用的任何 ORM 都在尝试序列化 Array 并将其转换为 YAML。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    相关资源
    最近更新 更多