简体   繁体   English

NoMethodError: 未定义方法 `<' 为 nil:NilClass

[英]NoMethodError: undefined method `<' for nil:NilClass

I'm adding a custom validation in my application while creating a coupon, start date of the validity for the coupon should be before the end date.我在创建优惠券时在我的应用程序中添加自定义验证,优惠券有效期的开始日期应该在结束日期之前。

validate :to_must_be_after_from

private
    def to_must_be_after_from
      if valid_to < valid_from
        self.errors[:base] << "Coupon cannot expire before the start of its validity period."
      end
    end

valid_to and valid_from are the date fields. valid_to 和 valid_from 是日期字段。


When I'm running this, NoMethodError occurred.当我运行它时,发生了 NoMethodError。 I have the following question regarding this,我对此有以下疑问,

  1. '<' is an operator and not a function, then how such error can occurs. '<' 是一个运算符而不是一个函数,那么这种错误是如何发生的。
  2. How to fix this and make the code function properly.如何解决此问题并使代码正常运行。

Most operators are actually methods in Ruby.大多数运算符实际上是 Ruby 中的方法。 This code:这段代码:

valid_to < valid_from

is merely syntactic sugar to只是语法糖

valid_to.<(valid_from)

The error message is pretty much self explanatory, you have to make sure valid_to and valid_from are not nil , using guard clause, for example, ie like this:错误消息几乎不言自明,您必须确保valid_tovalid_from不是nil ,例如使用保护子句,即像这样:

def to_must_be_after_from
  return if valid_to.blank? || valid_from.blank?

  # rest of the code
end

First you need to check whether valid from or valid to is blank or not.首先,您需要检查 valid from 或 valid to 是否为空白。 then you can check the value is less than or greater than .然后您可以检查该值是小于还是大于 。

def to_must_be_after_from

  return if valid_from.blank? || valid_to.blank?

  if valid_from < Date.today
    errors.add(:base, "You can't select past dates in valid from")
  elsif valid_to < valid_from
    errors.add(:base, "valid to can't be before the valid from date")
  end
end

Based on the error message-根据错误消息-

You are trying to compare variables in which one variable is nil .您正在尝试比较其中one variable is nil Can you check if both valid_to and valid_from are having proper values, before checking the validation - if valid_to < valid_from ?在检查验证之前,您能否检查valid_tovalid_from是否具有正确的值 - if valid_to < valid_from

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

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