【问题标题】:Ruby On Rails - Working out hour/days countdown by subtracting a DateTime column and DateTime nowRuby On Rails - 现在通过减去 DateTime 列和 DateTime 来计算小时/天倒计时
【发布时间】:2016-08-20 16:23:25
【问题描述】:

我基本上是在使用DateTime.now 在表格中设置DateTime 值列之前计算小时数(如果超过24 小时,则为x 天),但我所有的尝试都导致一个错误,我知道我必须做一些事情,比如尝试减去一个浮点数和一个字符串或其他东西......

我有一个question 表和一个fixture_date 列,这是一个datetime 类型列,到目前为止我已经尝试过:

  • question.fixture_date - DateTime.now
  • 错误:undefined method '-' for nil:NilClass

  • question.fixture_date - Date.today
  • 错误:undefined method '-@' for Tue, 26 Apr 2016:Date Did you mean? -

  • question.fixture_date - Time.now
  • 错误:undefined method '-' for nil:NilClass

它们都返回错误,正确的语法是什么?也许这与datetime 列有关,我应该使用替代方法吗?

【问题讨论】:

  • 错误信息是什么?顺便说一句,question.fixture_date.class 的结果是什么?
  • 我更新了错误消息 :-) 如果我反转它们,前两个返回 expected numeric,最后一个返回 can't convert nil into an exact number
  • 是的,这是你的fixture_date of question 的问题,只要确保它不是零
  • 啊,我在数据库中有一个NILL。我会全部更新并报告。
  • 我刚刚详细回答了您收到不同消息的原因,请检查并给我任何反馈:)

标签: sql ruby-on-rails ruby date datetime


【解决方案1】:

因为question.fixture_date 不是日期,在您的情况下是nilString,所以使用ruby stdlib 的Time::parse 方法,从字符串中获取有效时间,并捕获nil: 时的异常:

require 'time'

begin
  Time.parse(question.fixture_date) - Time.zone.now
rescue TypeError
  nil
end 

【讨论】:

  • 啊,这很酷 :-) 但是如何将它写入 HTML?除非我做错了什么,否则它不会写入页面。
【解决方案2】:

正如我所评论的,您的错误来自question,其中fixture_date = nil

解释错误信息:

  1. question.fixture_date - DateTime.now

    undefined method '-' for nil:NilClass
    

    因为 question.fixture_date 返回 nil 并且方法 - 不存在用于 NilClass。为了验证这一点,让我们运行:

    nil.methods.include?(:-)
    # => false
    
  2. DateTime.now - question.fixture_date

    TypeError: can't convert nil into an exact number
    

    因为 DateTime.now 的方法 - 确实存在,但参数 nil 无效。为了验证这一点,让我们运行

    Time.now.methods.include?(:-)
    # =>  true
    

总而言之,根本原因只是你的fixture_date = nil,尝试用简单的代码解决这个问题,例如:

<% if question.fixture_date %>
   <% delta = question.fixture_date - DateTime.now %>
   <!-- Your code here to use delta -->
<% end %>

否则,如果您想确保 fixture_date 不总是为零,请在您的 Question 模型中对其进行 Rails 验证

【讨论】:

  • 啊,这太棒了,感谢您提供的信息 :-) 有没有一种简单的方法可以让倒计时样式的东西正常工作?就像“还剩 2 天 3 小时”基于减去 datetime fixture_date 和 DateTime.now 代码?我会使用这种方法还是完全不同的方法?
  • 只要定义一个view helper来计算就可以了,这是如何计算stackoverflow.com/a/2311415/1789479,这里是如何定义一个view helper方法rails-dev.com/custom-view-helpers-in-rails-4
猜你喜欢
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多