2011-02-22 3 views
0

내 Rails 앱의 날짜/시간 필드에 문제가 있습니다. 내가 null 또는 빈 값 (코드 내 question 어제부터입니다) 유효 날짜 시간을 받아 들여야 검증을하고 있습니다 : 어떤 문자열로 datetime_field 설정할 때날짜/시간 필드는 문자열을 저장할 때 nil 값을 저장합니다.

include ActiveModel::Validations 
    class DateValidator < ActiveModel::EachValidator 
    def validate_each(record,attribute,value) 
     record.errors[attribute] << "must be a valid datetime" unless ((DateTime.parse(value) rescue nil)) 
    end 
    end 
    validates :datetime_field :date => true, :allow_nil => true, :allow_blank => true 

을, 내 모델 datetime_field의 이전 값을 무시하고 레일 콘솔에서 나는 다음과 같은 수 (전무로 설정 : 내 날짜 필드를 설정 중지하는 방법

object.update_attributes("datetime_field" => "Now") 
true 
object.datetime_field.nil? 
true 

전무 문자열로 업데이트 함과 동시에이 분야를 명시 적으로 빈 할 수있는 유지 후

에?

답변

2

를 반환해야 다음 생각인가 또는 비어 있습니다. 그러나 nil 또는 blank는 날짜가 될 수 없습니다. datetime_field should be DATE or BLANK or NIL : 그래서 당신 검증해야 같은 소리

include ActiveModel::Validations 
class DateOrBlankValidator < ActiveModel::EachValidator 
    def validate_each(record,attribute,value) 
    record.errors[attribute] << "must be a valid datetime or blank" unless value.blank? or ((DateTime.parse(value) rescue nil)) 
    end 
end 
validates :datetime_field :date_or_blank => true 

UPD 그냥 통지에 대한

. nil.blank? => true. 따라서 blank?인지 확인하려면 nil 인 경우 무언가를 검증 할 필요가 없습니다. Blank?은 빈 객체 및 무 객체에 대해 true를 반환합니다. "".blank? => true, nil.blank? => true

0

당신이십니까? r datetime_field가 마이그레이션에서 datetime으로 표시 되었습니까?

전달한 문자열이 유효한 datetime 문자열이 아니므로 datetime_field를 nil로 설정하면됩니다. 시도 대신이 일을 : datetime_field가 날짜이어야하며, 동시에이 전무가 될 수 있습니다

object.update_attributes("datetime_field" => "2010-01-01") 
true 

것은

object.datetime_field 

당신 검증이 이상한

2010-01-01 
관련 문제