Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `>' for nil:NilClass Ruby on Rails (NoMethodError)

So for some odd reason I keep getting this error:

undefined method `>' for nil:NilClass
Rails.root: C:/Sites/booking_saloniser - Calendar

 Application Trace | Framework Trace | Full Trace
 app/models/user.rb:11:in `block in upcoming_appointments'
 app/models/user.rb:11:in `upcoming_appointments'
 app/controllers/appointments_controller.rb:8:in `index'

appointment controller

def index
  @upcoming_appointments = current_user.upcoming_appointments
end

user model

  def upcoming_appointments
    appointments.order(appointment_time: :desc).select { |a| a.appointment_time > (DateTime.now) }
  end

Any chance someone could help me get around this error?

like image 788
Razz Avatar asked Jun 02 '26 06:06

Razz


1 Answers

It appears one or more of your appointment records has a nil appointment_time.

If this is not expected, you should add a validation on the model that it's not null, and fix your existing data.

Otherwise (and this works as quick fix), you can chain a query to not include records with a nil appointment time:

  def upcoming_appointments
    appointments
      .order(appointment_time: :desc)
      .where.not(appointment_time: nil)
      .select { |a| a.appointment_time > (DateTime.now) }
  end

If where.not isn't available (if you're using an older version of rails), you can also use where("appointment_time != null")

like image 134
max pleaner Avatar answered Jun 05 '26 00:06

max pleaner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!