Razz
Razz

Reputation: 39

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?

Upvotes: 3

Views: 1469

Answers (1)

max pleaner
max pleaner

Reputation: 26768

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")

Upvotes: 2

Related Questions