[英]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
. 看来您的一个或多个约会记录的
appointment_time
为nil。
If this is not expected, you should add a validation on the model that it's not null, and fix your existing data. 如果不希望出现这种情况,则应在模型上添加一个非null的验证,然后修复现有数据。
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")
如果
where.not
不可用(如果您使用的是旧版的rails),则还可以使用where("appointment_time != null")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.