开发者

Rails: Error "NoMethodError: undefined method `<' for nil:NilClass", missing some gem?

Here is model class 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 

Here is log of 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


It's complaining because the start_date and end_date attributes have not been set when it gets to your custom validation. When it tries to compare the start_date with today's date, it's trying to compare a nil value.

You could wrap your validation in a conditional block:

if !start_date.nil? && !end_date.nil?
  ...
end


Notice that Item object you create in the console has a start_date, end_date, etc. of nil.

The comparison, then, of nil < Date.today in your validation method is causing the exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜