2011-02-22 103 views
0

我的Rails應用程序中的日期時間字段存在問題。我有一個應該接受的有效日期時間驗證,並允許空值或空值(代碼是從我question昨天):保存字符串時日期時間字段保存零值

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一些字符串時,我的模型覆蓋datetime_field的前值和它設置爲零(在軌控制檯我得到如下:

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

如何停止設置我的時間字段,以比零串更新,並同時保持能夠空白這一領域明確後

回答

2

您驗證很奇怪:datetime_field應該是一個日期,而在同一時間,它可以是零或空白。但無或空白不能是日期。因此,您的驗證應該聽起來像: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?,那麼您不需要驗證它是否爲nilBlank?將爲空對象和零對象返回true:"".blank? => true,nil.blank? => true

0

是你在遷移中將datetime_field標記爲日期時間?

如果是這樣datetime_field被設置爲nil becouse字符串,你傳遞的是無效的日期時間字符串。儘量不要做這樣的:

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

是假設然後

object.datetime_field 

應該返回

2010-01-01