【问题标题】:Custom Validator to Prevent an appointment from being scheduled too early in day?自定义验证器以防止约会被安排得太早?
【发布时间】:2014-12-31 08:09:14
【问题描述】:

我正在构建一个具有 Appointment 模型的 Rails 4 应用程序。我试图弄清楚如何编写自定义验证器以防止用户在上午 6:30 之前和晚上 9:00 之后安排约会。 DateTime 是我模型的约会日期字段的数据类型。

我最初的想法是在我的模型中编写一个方法来定义验证,但我不知道如何构建这样的方法,或者这是否是解决问题的最佳方法。

我在互联网上搜索了有关如何实现我的目标的线索,但没有发现任何有用的信息。对于如何最好地做到这一点的任何建议,我将不胜感激。

【问题讨论】:

    标签: ruby-on-rails validation datetime


    【解决方案1】:

    您可以创建自己的,就像活动记录一样。这会产生干净、便携、易于测试的自定义验证。一个示例可能如下所示:

    使用以下命令创建 app/validators/during_business_hours_validator.rb

    class DuringBusinessHoursValidator < ActiveModel::EachValidator
    
      def validate_each(record, attribute, value)
        # example - do whatever you want here
        unless value.present? && during_business_hours(value)
          record.errors[attribute] << 'must be during business hours'
        end
      end
    
      def during_business_hours(time)
        # from http://stackoverflow.com/q/10090962/525478
        Range.new(
          Time.local(time.year, time.month, time.day, 6, 30),
          Time.local(time.year, time.month, time.day, 21)) === time
      end
    
    end
    

    然后,在您的模型中添加:

    validates :appointment_date,
              during_business_hours: true
    

    【讨论】:

    • 感谢您的回复。我正在学习 Rails,并没有完全理解建议,尤其是第一种方法。我不明白第一种方法的作用或工作原理。我是否可以用一些东西来代替方法的“记录、属性、值”部分?请解释第一种方法的作用,以及我应该如何使用它。当你说“在这里做任何你想做的事”时,你是什么意思?相对于我的目标,我可以在方法的那部分放置什么样的东西?最后,我可以将这个自定义验证器放在 Rails 文件树中的任何位置吗?非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    相关资源
    最近更新 更多