2016-07-20 38 views
1

我正在使用Rails 4並嘗試格式化從SQLite數據庫中拉出的日期時間。我在模型中工作,但對象類表現得非常奇怪。在Rails 4中顯示爲零的日期時間

如果鍵入: Duration <%= micropost.duration %>

然後打印出完整的日期時間。我只想要時間。

如果鍵入: Duration <%= micropost.duration.strftime("%H:%M:%S") %>

然後我得到的錯誤: undefined method的strftime」的零:NilClass`

所以我嘗試打字: Duration <%= micropost.duration.class %>

,並返回類型: ActiveSupport::TimeWithZone

看起來它有時會識別類型,有時不識別。爲了解決這個問題,在IRB中,strftime("%H:%M:%S")方法起作用。

How to format time and date from db:datetime record in Rails 4中發生了類似的問題,但該解決方案無效。我甚至看在正確的地方?

+0

你的微博是否在循環內? – power

回答

1

我想你正在嘗試它內循環和任何micropost持續時間爲零。試試這個

Duration <%= micropost.duration.strftime("%H:%M:%S") if micropost.duration.present? %> 
+0

是的。這是問題。不知何故,我的種子數據沒有填充Times。謝謝! – MikeK