简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM