开发者

Validate Datetime in rails

开发者 https://www.devze.com 2023-03-08 01:28 出处:网络
I am trying to validate two date fields. I want to validate开发者_开发百科 that the second field is always the same date or any date after the first one.

I am trying to validate two date fields. I want to validate开发者_开发百科 that the second field is always the same date or any date after the first one.

Example if date1 is 22/05/2011 date2 can not be 20/05/2011.

I am using ruby on rails 3.0.7, and I am trying to do this at the model level.


See that post: Rails 3 Datetime validation

and also:

Rails 3 custom validation between datetime :)


a.) there's an app for that

gem "validates_date_time", :git => "git://github.com/sofatutor/validates_date_time", :branch => 'rails-3'

b.) I'm actually not using that gem because I found this handy model method before the gem

class KeyPerson < ActiveRecord::Base

validate :started_at_is_date?

private

def started_at_is_date?
   if !started_at.is_a?(Date)
     errors.add(:started_at, 'must be a valid date') 
   end
  end
  end

where :started_at is the column's name. That's a little bit of ruby magic/chaos for you with the dynamic method name handling thing

0

精彩评论

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