Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method nil "group_by"

I'm overlooking what should be a simple solution. I keep getting the error:

NoMethodError in LifetimesController#index
undefined method `deadline' for #<Class:0x007f88a3c19bb0>

This is because one of the lifetime challenges has a nil :deadline. Adding deadlines are optional.

How can I group_by only the lifetime challenges that have a :deadline present?

controller

def index
  @lifetimes = current_user.lifetimes.unaccomplished
  @lifetime_months = @lifetimes.group_by { |t| t.deadline.beginning_of_month }
end

model

scope :unaccomplished, -> { where(accomplished: nil) }

schema

  create_table "lifetimes", force: true do |t|
    t.string   "name"
    t.date     "deadline"
    t.boolean  "accomplished"
    t.integer  "user_id"
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
  end

I was unsuccessful in adding a nil or .present? conditional to any of the above code.

like image 240
AnthonyGalli.com Avatar asked Mar 08 '26 00:03

AnthonyGalli.com


1 Answers

Here's the solution that finally worked:

scope :unaccomplished, -> { where.not(deadline: nil) }

I tried very similar things in the past, but only this seemed to work. Thanks for the help!

like image 184
AnthonyGalli.com Avatar answered Mar 10 '26 16:03

AnthonyGalli.com