【问题标题】:haml collection and nil --> strftimehaml 集合和 nil --> strftime
【发布时间】:2010-11-18 17:20:18
【问题描述】:

我有一个 Post 对象,我正在部分渲染,其中一个元素是

= post.created_at

我想格式化时间,所以我尝试了部分 strftime 的变体并作为模型钩子。

= post.created_at.strftime('etc etc')
&
= post.formatted_time

当有要渲染的东西时这些工作正常,但是当没有一组帖子时,渲染页面就会出错:

undefined method `strftime' for nil:NilClass

只有第一个在没有帖子时有效,并在页面上创建 1 个空的帖子 div。

我需要在模型或模板中做一些事情来捕捉它何时为空并且什么都不渲染,这似乎很基本,但我还没有找到正确的搜索词来找到我理解的实现。

我发布这个是为了有人可以帮助我思考到目前为止我所拥有的东西。基本上我需要格式化时间,我可以这样做,但在没有什么可以格式化的时候捕获。

【问题讨论】:

    标签: ruby conditional haml null strftime


    【解决方案1】:

    在 Rails 中你总是可以使用try,它只会在 created_at 不为 nil 时运行该方法:

    = post.created_at.try(:strftime, 'etc etc')
    

    http://apidock.com/rails/Object/try

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      相关资源
      最近更新 更多