开发者

Datetime field saves nil value when saving a string

开发者 https://www.devze.com 2023-02-12 19:59 出处:网络
I have a problem with Datetime field in my Rails app. I have a validation that should accept valid Datetime, and allows null or blank values (code is from my question yesterday):

I have a problem with Datetime field in my Rails app. I have a validation that should accept valid Datetime, and allows null or blank values (code is from my question yesterday):

  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

However, when set datetime_field to some string, my model overrides the previous value of datetime_field and sets it to nil (in rails console I get the following:

object.update_attributes("datetime_field" => "Now")
true
object.datetim开发者_Go百科e_field.nil?
true

How to stop setting my datetime field to nil after updating with string, and at the same time keep being able to blank this field explicitly?


You validations are strange: datetime_field should be a date and at the same time it can be nil or blank. But nil or blank can't be date. So your validation should sounds like: 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

Just for notice. nil.blank? => true. So you never need to validate something if it is nil if you are checking if it is blank?. Blank? will return true for empty objects and for nil objects: "".blank? => true, nil.blank? => true


Is your datetime_field marked as datetime in your migration?

If so datetime_field is being set to nil becouse string you've passed isn't valid datetime string. Try doing this instead:

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

Is suppose then

object.datetime_field

should return

2010-01-01
0

精彩评论

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