加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:29:25 所属栏目:百科 来源:网络整理
导读:我的模型有两个字段,我想作为验证的一部分相互比较.我想确保end_time在start_time之后.我已经写了一个验证方法来比较它们,但我必须做错事情,因为这些值总是为零.有人可以帮忙吗? class LogEntry ActiveRecord::Base validates :start_time,:presence = { :m
我的模型有两个字段,我想作为验证的一部分相互比较.我想确保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,因为如果在多个表单元素上创建时间可能会有趣的事情发生.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读