ruby-on-rails – 比较两个字段的Rails验证方法?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 比较两个字段的Rails验证方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的模型有两个字段,我想作为验证的一部分相互比较.我想确保end_time在start_time之后.我已经写了一个验证方法来比较它们,但我必须做错事情,因为这些值总是为零.有人可以帮忙吗?
class LogEntry < ActiveRecord::Base
  validates :start_time,:presence => { :message => "must be a valid date/time" }
  validates :end_time,:presence => {:message => "must be a valid date/time"}
  validate :start_must_be_before_end_time

  def start_must_be_before_end_time
    errors.add(:start_time,"must be before end time") unless
       start_time > end_time
  end 
end

得到错误

undefined method `>' for nil:NilClass

所以,start_time和/或end_time为零.我以为我是跟随我发现的很多例子,但显然不是.我失踪了什么

谢谢.

解决方法

我最好的猜测是你需要你的方法看起来像这样:
private

def start_must_be_before_end_time
    errors.add(:start_time,"must be before end time") unless
        start_time < end_time
end

(另外,请注意<而不是>(或更改为if和> =)

如果这不起作用,那么您还应该检查在控制器中正确定义start_time和end_time,因为如果在多个表单元素上创建时间可能会有趣的事情发生.

原文链接:https://www.f2er.com/ruby/273488.html

猜你在找的Ruby相关文章