0

여기에 모델 클래스 클래스 항목 : 항목 < 액티브 :: 자료 validates_presence_of입니다 validate_start_and_end_date을 여기에레일 : 오류 "NoMethodError : 정의되지 않은 메소드`< 'for nil : NilClass", 일부 보석이 누락 되었습니까? 유효성을 PRODUCT_ID : 시작일 : : 종료일,

  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 

입니다 레일 콘솔의 로그

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 

답변

1

콘솔에 만들는 Item 개체의 크기가 start_date, end_datenil입니다.

유효성 검사 방법에서 nil < Date.today을 비교하면 예외가 발생합니다.

+0

. 'Item :: Item' 모델을 게시 할 수 있습니까? (그것은 같은 문제 일지 모르지만 나는 확신 할 수 없다.) –

2

사용자 정의 유효성 검사를 시작할 때 start_date 및 end_date 속성이 설정되지 않았기 때문에 불편합니다. start_date와 오늘 날짜를 비교하려고 시도 할 때 nil 값을 비교하려고합니다.

당신은 조건부 블록에 검증을 포장 수 : 난 그냥 첫 번째 코드 블록은 '강의 :: Lecture` 모델을 설명하는보고

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

'start_date.nil이 아닌 한? && end_date.nil?' – Noz

관련 문제