Home > Enterprise >  NoMethodError - undefined method `strftime` for nil:NilClass
NoMethodError - undefined method `strftime` for nil:NilClass

Time:07-18

I am trying to use the gem 'strftime' in my Ruby project. Here is how I am using it in my code:

TaskController: class TasksController < ApplicationController

    get '/tasks' do 
        Task.all.to_json(methods: [:date_format, :category])
      end
    
      get '/tasks/:id' do 
        Task.find(params[:id]).to_json
      end
    
      post '/tasks' do 
        category = Category.find_by(name: params[:category])
        task = Task.create(
          description: params[:description],
          completed: false,
          due_by: params[:due_by],
          reminder: params[:reminder],
          category: category
        )
        task.to_json(methods: [:date_format, :category])
      end
    
      patch '/tasks/:id' do
        task = Task.find(params[:id])
        task.update(
          completed: params[:completed],
          reminder: params[:reminder]
        )
        task.to_json
      end
    
      delete '/tasks/:id' do
        task = Task.find(params[:id])
        task.destroy
        task.to_json
      end
    
      delete '/categories/:id' do
        category = Category.find(params[:id])
        category.destroy
        category.to_json
      end

end

Task Model:

class Task < ActiveRecord::Base 
    belongs_to :category 

    def date_format
        due_by.strftime("%a, %b %-d %Y")
    end

  
end

When I start my rake server, I get the following error:

NoMethodError - undefined method `strftime' for nil:NilClass
Did you mean?  strfd:

I am not sure why this is coming up with undefined method. Do you see any problems with the code? Thank you!

CodePudding user response:

Most probably your due_by is nil, no value is set on the particular record you are showing.

You must have a handling for this case or make sure due_by is always present by having a presence validation (or have a db validation on top).

One solution to handle nil due_by is this:

class Task < ActiveRecord::Base
    belongs_to :category

    def date_format
        due_by&.strftime("%a, %b %-d %Y") # By adding `&.`
    end
end
  • Related