ruby - 验证一个日期时间晚于另一个日期时间

标签 ruby datetime ruby-on-rails-4

当我尝试验证模型中的两个 Datetime 属性时,我得到以下信息:

undefined method `to_datetime' for nil:NilClass

它突出了我的功能

def validate_timings
    if (startDate > endDate)
        errors[:base] << "Start Time must be less than End Time"
    end
end

特别是 '>' 的使用

我认为这可能是我处理日期的方式,但我不确定。日期是这样传递的:

"startDate(1i)"=>"2013",
 "startDate(2i)"=>"12",
 "startDate(3i)"=>"18",
 "startDate(4i)"=>"10",
 "startDate(5i)"=>"24",
 "endDate(1i)"=>"2013",
 "endDate(2i)"=>"12",
 "endDate(3i)"=>"18",
 "endDate(4i)"=>"11",
 "endDate(5i)"=>"24",

P.S 我知道我的命名约定不正确,我会在下一次迁移中更改它们。

更新:这是我的完整模型

   class Appointment < ActiveRecord::Base
    belongs_to :car
    belongs_to :service
    accepts_nested_attributes_for :service
    accepts_nested_attributes_for :car

    attr_accessor :period, :frequency, :commit_button

    validates_presence_of :car_id, :service_id, :startDate, :endDate
    validate :validate_timings


    def validate_timings
        p startDate, endDate
        if (startDate > endDate)
            errors[:base] << "Start Time must be less than End Time"
        end
    end

    def update_appointments(appointments, appointment)
        appointments.each do |e|
            begin
                st, et = e.startDate, e.endDate
            e.attributes = appointment

            nst = DateTime.parse("#{e.startDate.hour}:#{e.startDate.min}:#{e.startDate.sec}, #{st.day}-#{st.month}-#{st.year}")
            net = DateTime.parse("#{e.end.hour}:#{e.end.min}:#{e.end.sec}, #{et.day}-#{et.month}-#{et.year}")
            #puts "#{nst}           :::::::::          #{net}"
            rescue
            nst = net = nil
        end
        if nst and net
            #          e.attributes = appointment
            e.startDate, e.endDate = nst, net


           e.save
        end
    end

  end
end

最佳答案

您的比较运算符是正确的。但是,当您在日期时间对象上调用此运算符时,它会尝试将右侧对象转换为另一个日期时间对象。

即:“Time.now < nil”将返回: “NoMethodError: undefined method `to_datetime' for nil:NilClass”而不是无效日期错误。

所以在您的情况下,您得到的错误意味着您在尝试比较它们时没有正确的日期时间 endDate

您似乎在模型的对象有时间加载其 endDate 值之前调用了验证方法。

关于ruby - 验证一个日期时间晚于另一个日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20655633/

相关文章:

ruby-on-rails - 使用 open() 方法在 Rails 中创建/重命名临时文件

html - `input' 的未定义方法 "NoMethodError in Revisers#new "

ruby - 如何使带有 Hstore 的 PostgreSQL 在 Sinatra 简单应用程序中工作?

python - ISO 时间到 python 中的人类可读时间

python - 在Python中将UTC转换为另一个时区的简单方法

ruby-on-rails - 为什么运行 Rspec 时会出现未定义方法 'have' 错误?

ruby-on-rails - 清除 Rspec 匹配器以进行更改(模型,:count). by(1)

ruby - 有没有办法并行运行 cucumber 场景

mongodb - 使用 where 条件聚合查询

javascript - 处理 CRUD 资源的 AngularJS "way"是什么