【问题标题】:rails custom validator doesn't seem to workrails 自定义验证器似乎不起作用
【发布时间】:2012-10-30 13:16:36
【问题描述】:

我在 lib/readiness_for_completion_validator.rb 中编写了一个自定义验证器:

class DisruptionTimeValidator < ActiveModel::Validator
  def validate(record)
    # if record.timeline.events[0].event_time > record.timeline.events[1].event_time 
    if true 
      record.errors[:Outage] << " end time needs to be after outage begin time" 
    end
  end
end

问题是,如果我用“if true”代替注释掉的行,我永远无法触发它。

我在 Rails 控制台中测试了该条件,它完全按照我的意愿工作,但它在验证器中永远不会评估为 true...

任何帮助将不胜感激,我花了很多时间研究这个,这让我发疯:(

我有一个包含许多事件的时间线。人们可以根据事件调整 event_time,但每个时间线包含两个需要连续发生的特殊事件。

请在下面找到我在 app/models/event.rb 中的内容:

class Event < ActiveRecord::Base
  attr_accessible :event_description, :event_time, :timeline_id

  belongs_to :timeline

  validates :event_description, :length => { :in => 10..255 }

  validates_with DisruptionTimeValidator, :on => :update

end

(我弄乱了 :on 但没有任何区别)

任何帮助将不胜感激,

非常感谢!

【问题讨论】:

    标签: ruby-on-rails-3 model relationship validation


    【解决方案1】:

    我想通了...我的验证器是正确的,我通过在控制器中对事件进行排序然后保存时间线来搞砸事情...所以当新事件被添加到 events[0] 和 events[1 ] 被其他事件取代...

    【讨论】:

      猜你喜欢
      • 2011-04-17
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      相关资源
      最近更新 更多