Heroku上的NoMethodError,但不是本地的

我正在为Rails中的期刊开发一个网站,并且在我的一个页面上列出了按降序发布的每个问题。 我还有一个选择框供用户按年度过滤问题,因为他们没有名字但希望如果问题中的文章没有上传到网站,它将帮助他们更快地找到他们正在寻找的内容分别。

为了创建filter框的选项,我做了以下函数来返回问题的所有唯一年份的列表(问题有一个日期字段,即问题的发布日期,以防出现之前的旧问题网站需要上传)。

Issue.select("date").order('date desc').map{ |i| i.date.year }.uniq

此function在我自己的机器上运行良好但是当我在Heroku(一个免费帐户)上部署它时,它在我检查日志时给出以下错误消息。

 2017-08-15T15:19:42.521061+00:00 app[web.1]: Started GET "/issues" for 83.136.45.169 at 2017-08-15 15:19:42 +0000 2017-08-15T15:19:42.522804+00:00 app[web.1]: Processing by IssuesController#index as HTML 2017-08-15T15:19:42.524822+00:00 app[web.1]: Issue Load (0.9ms) SELECT "issues"."date" FROM "issues" ORDER BY date desc 2017-08-15T15:19:42.525378+00:00 app[web.1]: Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.9ms) 2017-08-15T15:19:42.525925+00:00 app[web.1]: 2017-08-15T15:19:42.525926+00:00 app[web.1]: NoMethodError (undefined method `year' for nil:NilClass): 2017-08-15T15:19:42.525927+00:00 app[web.1]: app/controllers/issues_controller.rb:12:in `block in index' 2017-08-15T15:19:42.525927+00:00 app[web.1]: app/controllers/issues_controller.rb:12:in `index' 

自从我上次推送以来,我没有对数据库进行任何更改。 我不确定如何进一步调试这种情况。

该错误不是由heroku引起的,而是由heroku数据库中的数据引起的。 您似乎在Issue表中创建了没有日期的记录。

要避免这种情况,请使用以下查询:

 Issue.where.not(date: nil).select("date").order('date desc').map{ |i| i.date.year }.uniq 

我认为上面的查询仅适用于Rails 5.如果您使用以前的版本,您可以这样做:

 Issue.select("date").order('date desc').map{ |i| i.date&.year }.uniq.compact 

注意i.date&.year和compact。 如果datenil&将不会执行以下方法。 但是,它可能会向您的数组添加nil对象,从而产生如下内容:

 [year1, year2, nil, year3] 

compact将删除nil对象,以获得:

 [year1, year2, year3] 

更多信息: http : //mitrev.net/ruby/2015/11/13/the-operator-in-ruby/