【问题标题】:Date validation helper for mongoid/active model?mongoid/活动模型的日期验证助手?
【发布时间】:2011-06-09 02:39:47
【问题描述】:

是否有任何用于 mongoid 或活动模型的日期验证助手? 我想检查有效 ISO_8601 标准 (http://en.wikipedia.org/wiki/ISO_8601#Dates) 的日期,这与 mongoids validates_format_of 无关紧要。但日期应该是将来或取决于字段 >= 另一个日期(开始日期和结束日期)。

我的方法是使用validates_format_of 检查格式并编写我自己的日期验证器以满足我的进一步要求。

以前有人做过吗?

谢谢, 朱利安

【问题讨论】:

    标签: ruby-on-rails validation date mongoid


    【解决方案1】:

    您的方法似乎不错。最好的方法是将验证分解到它自己的函数中。

    你可以这样做:

    class Foo
       include Mongoid::Document
       field :date_time, :type => DateTime
       validate :date_is_ok?
    
       def date_is_ok
         unless self.date_time.to_i > Time.now.to_i
            errors.add :date_time, "must be in the future"
            return false
         end
         true
       end
    end
    

    【讨论】:

    • 感谢您的回答。我现在使用 validates_timeliness 进行日期/时间验证。
    【解决方案2】:

    是的,validates_timeliness 对 Rails 3.x 和 ActiveModel 的日期、时间和日期时间进行了完整的验证。

    它明确支持 Mongoid:

    ValidatesTimeliness.setup do |config|
    
      # Extend ORM/ODMs for full support (:active_record, :mongoid).
      config.extend_orms = [ :mongoid ]
    
    end
    

    【讨论】:

    • 谢谢!我现在正在使用 validates_timeliness,它解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多