【问题标题】:Custom Method Validation Error in Rails ControllerRails 控制器中的自定义方法验证错误
【发布时间】:2014-04-21 15:26:27
【问题描述】:

我是 Rails 的新手,所以请原谅这个问题。我最近遇到了一个问题,如果有人可以帮助找到正确的解决方案,我将不胜感激。

我想将此自定义方法添加到我的验证中。一旦用户提交的开始日期超过了结束日期,它应该会引发错误

class Request < ActiveRecord::Base
    validates :start_date, :to_date, presence: true
    validates :checkin_date_cannot_be_in_the_past

    def checkin_date_cannot_be_in_the_past 
        if :date > :todate
        errors.add(:date, "can't be in the past") 
    end 
end

不幸的是,这个自定义方法对我不起作用,就像 Active Record Validations 文档中描述的那样,并且在我的控制器中引发了一个错误(语法错误、意外的输入结束、期望关键字_end):

  def new
   @request = Request.new
  end 

花了一些时间研究后,我找不到合适的解决方案,所以我希望这里有人可以提供帮助?

干杯

罗伯

【问题讨论】:

  • 您需要调用此方法 checkin_date_cannot_be_in_the_past 进行验证,这里的 date & todate 是什么?
  • 对不起,这只是一个错字(刚刚编辑)。我实际上确实打电话 checkin_date_cannot_be_in_the_past
  • 您缺少一个 if 条件的结尾,这就是您收到语法错误的原因

标签: ruby-on-rails validation activerecord


【解决方案1】:

这应该是验证调用自定义验证而不是验证

class Request < ActiveRecord::Base
  validates :start_date, :to_date, presence: true
  validate :checkin_date_cannot_be_in_the_past

  def checkin_date_cannot_be_in_the_past 
    errors.add(:date, "can't be in the past") if date > todate
  end 
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多