Brian McNestry
Brian McNestry

Reputation: 155

NoMethodError on Heroku but not locally

I am developing a website for a journal in Rails and on one of my pages has a list of every single issue that has been published in descending order. I also have a select box for users to filter the issues by year as they don't have names but hopefully, it will help them to find what they are looking for more quickly if the article within an issue isn't uploaded to the site separately.

In order to create the options for the filter box, I made the following function to return a list of all the unique years for the issues (an Issue has a date field that is the publish date of the issue, in case old issues that precede the website need to be uploaded).

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

This function works excellently on my own machine but when I deploy it on Heroku (a free account), it gives the following error message when I check the logs.

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'

I have made no changes to the database since my last push. I'm not sure how to further debug this situation.

Upvotes: 0

Views: 161

Answers (1)

Graham Slick
Graham Slick

Reputation: 6870

The error is not caused by heroku, but by the data you have in the database on heroku. You seem to have records in the Issue table that were created without a date.

To avoid this, use this query:

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

I think the query above works only with Rails 5. If you use a previous version, you can do this:

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

Notice the i.date&.year and the compact. The & will not execute the following method if date is nil. However, it will probably add nil objects to your array, resulting in something like this:

[year1, year2, nil, year3]

compact will remove nil objects, to obtain this:

[year1, year2, year3]

More information: http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/

Upvotes: 1

Related Questions