繁体   English   中英

nil:NilClass Ruby on Rails的未定义方法'>'(NoMethodError)

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

因此,出于某些奇怪的原因,我不断收到此错误:

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'

任命控制器

def index
  @upcoming_appointments = current_user.upcoming_appointments
end

用户模型

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

有人可以帮助我解决这个错误吗?

看来您的一个或多个约会记录的appointment_time为nil。

如果不希望出现这种情况,则应在模型上添加一个非null的验证,然后修复现有数据。

否则(这是快速解决方案),您可以将查询链接为不包括约会时间为零的记录:

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

如果where.not不可用(如果您使用的是旧版的rails),则还可以使用where("appointment_time != null")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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