【问题标题】:undefined method `to_date' for nil:NilClass on datetime fieldnil:NilClass 在日期时间字段上的未定义方法“to_date”
【发布时间】:2013-12-20 17:18:57
【问题描述】:

在我看来,我在打电话

<% @posts.each do |post| %>
  ...
  <%= post.published_on.to_date %>
  ...
<% end %>

“published_on”是我帖子数据库中的日期时间字段:

#schema.rb
t.datetime "published_on"

在我的控制器中,我使用“现在”方法进行设置:

    def publish
      ...
      @post.published_on=DateTime.now
      ...
      end
    end

当页面加载时,我收到以下错误:

undefined method `to_date' for nil:NilClass

但是,如果我在视图中删除 'to_date' 方法,页面加载正常,并且 published_on 字段将填充,例如,'2013-12-20 17:05:40 UTC'

我的问题是,为什么会出现此错误? 'to-date' 方法有效吗?

【问题讨论】:

  • 你有什么问题?
  • 已更新问题。
  • 如果published_on 已经返回了有效的日期格式,请问您为什么要使用to_date?也许您的意思是使用strftime()
  • strftime() 可以解决问题,谢谢 :)
  • 更新日期时间@post.published_on=DateTime.now987654329@后你的记录是否保存在@post.published_on=DateTime.now

标签: ruby datetime activerecord ruby-on-rails-4


【解决方案1】:

你可能打算使用

<%= @post.published_on.to_date %>

注意使用实例变量@post而不是局部变量post

【讨论】:

  • 好眼光,但该行实际上是在@post 上的一个循环中,我已将其添加到问题中。不过,谢谢,这对澄清很有帮助。
【解决方案2】:

多诺万回答了这个问题。数据已经是日期格式,我想做的是格式化,而正确的方法是使用strftime()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多