2015-01-12 7 views
0

실패하지 I 모델 필드에서 다음 검증이 있습니다레일 검증

validates :invoice_date, :presence => true, :unless => Proc.new { |invoice| invoice.invoice_date.future? } 

그것은 아주 간단 보이지만, 그것이 작동하지 않습니다. 미래가되면 오류가 발생하지 않습니다. 이 경우 Proc은 실제로 false을 반환합니다.

유효성 검사 오류가 표시되지 않는 이유는 무엇입니까?

+0

날짜가 추후에 오류가 발생하기를 원하십니까? – Ajay

+0

예, 이것은 의도 한 동작입니다. – linkyndy

+0

downvote에 대한 이유를 언급해야합니다. –

답변

2
validates :invoice_date, :presence => true 
validate :is_future_invoice_date? 

private 
def is_future_invoice_date? 
    if invoice_date.future? 
    errors.add(:invoice_date, 'Sorry, your invoice date is in future time.') 
    end 
end 

존재 단순히 보장 사실, invoice_date이 있어야합니다. 날짜가 미래 날짜인지 또는 사용자 정의 유효성 검사 방법을 지정하지 않았는지 확인 (is_future_invoice_date?) 날짜가 미래의 날짜 인 경우이 메소드는 invoice_date 속성에 대해 오류 메시지를 추가합니다. 여기

상세 정보 : http://guides.rubyonrails.org/active_record_validations.html#custom-methods

+1

나는 당신이 당신의 대답을 조금 더 자세히 설명 할 수 있다고 생각합니다. 이 코드는 유용하지만 아무 것도 설명하지 않습니다. –

+1

추가 설명 :) – Ajay

0

그런 시도 : -

validate check_invoice_date_is_future 

def check_invoice_date_is_future 
if invoice_date.present? 
    errors.add(:invoice_date, "Should not be in future.") if invoice_date.future? 
else 
    errors.add(:invoice_date, "can't be blank.") 
end 
end 
3

조건은 유효성 검사를 실행하거나하지 말아야하는 경우 결정을위한 '않는', 그것이 성공하거나 실패하지 않을 경우. 그래서 귀하의 유효성 검사는 본질적으로 "invoice_date가 존재하지 않으면 invoice_date가 존재하지 않는 경우 유효성을 검사합니다."(의미가 없음)

두 가지 유효성 검사, 존재 여부 및 날짜를 ​​원하는 것처럼 들립니다. 펜싱.

validate :invoice_date_in_past 

def invoice_date_in_past 
    if invoice_date.future? 
    errors.add(:invoice_date, 'must be a date in the past') 
    end 
end 
+0

오,이 문서는 충분히 명확하지 않았습니다 (적어도 나를 위해). 명확히하고 수정 해 주셔서 감사합니다. – linkyndy