这是模型类 class Item :: Item<的ActiveRecord :: Base的 validates_presence_of:start_date,:end_date,:product_id validate:validate_start_and_end_date
def validate_start_and_end_date
errors.add(:start_date, "should not be in past") if start_date < Date.today
errors.add(:end_date, "should not be in past") if end_date < Date.today
errors.add(:base, "start date should not be after end date") if end_date < start_date
end
belongs_to :product, {:class_name => 'Item::Product'}
end
这是rails console的日志
ruby-1.8.7-p334 :020 > item = Item::Item.new
=> #<Item::Item id: nil, start_date: nil, end_date: nil, product_id: nil>
ruby-1.8.7-p334 :021 > item.valid?
NoMethodError: undefined method `<' for nil:NilClass
from /home/maddy/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-3.0.3/lib/active_support/whiny_nil.rb:48:in `method_missing'
from /media/Development/codie/orgstud-security/app/models/lecture/lecture.rb:13:in `validate_start_and_end_date'
from /home/maddy/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-3.0.3/lib/active_support/callbacks.rb:419:in `_run_validate_callbacks'
from /home/maddy/.rvm/gems/ruby-1.8.7-p334/gems/activemodel-3.0.3/lib/active_model/validations.rb:212:in `run_validations!'
from /home/maddy/.rvm/gems/ruby-1.8.7-p334/gems/activemodel-3.0.3/lib/active_model/validations/callbacks.rb:67:in `run_validations!'
from /home/sgarg/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-3.0.3/lib/active_support/callbacks.rb:413:in `_run_validation_callbacks'
from /home/maddy/.rvm/gems/ruby-1.8.7-p334/gems/activemodel-3.0.3/lib/active_model/validations/callbacks.rb:67:in `run_validations!'
from /home/maddy/.rvm/gems/ruby-1.8.7-p334/gems/activemodel-3.0.3/lib/active_model/validations.rb:179:in `valid?'
from /home/maddy/.rvm/gems/ruby-1.8.7-p334/gems/activerecord-3.0.3/lib/active_record/validations.rb:55:in `valid?'
from (irb):21
答案 0 :(得分:2)
它抱怨,因为在进入自定义验证时尚未设置start_date和end_date属性。当它试图将start_date与今天的日期进行比较时,它试图比较一个零值。
您可以将验证包装在条件块中:
if !start_date.nil? && !end_date.nil?
...
end
答案 1 :(得分:1)
请注意,您在控制台中创建的Item
对象包含start_date
的{{1}},end_date
等。
然后,验证方法中nil
的比较导致异常。