正确提交参数后验证失败

时间:2019-02-11 03:23:16

标签: ruby-on-rails

Rails 3.2
date_validator gem v 0.9.0

在我的invoices_controller.rb中,我有:

def submit_for_payment
  if params.has_key?("confirm_manual_processing")
     if !params[:manual_reference].empty? && !params[:manually_paid_at].empty?
      @records = Invoice.document_manual_payments_to_service_providers params
    else
      flash[:error] = "Reference Number Date Paid Both Required"
    end
  else
    if !params[:manual_reference].empty? || !params[:manually_paid_at].empty?
      flash[:error] = "Reference Number Date Paid Both Required AND you must confirm by checking the manual payment box"
    else
      @records = Invoice.pay_invoices_to_service_providers params[:invoices]
    end
  end
  redirect_to [ params[:redirect_path] || :needed_to_be_paid, :admin, :invoices ]
end

在我的invoices.rb中,我有:

attr_accessible :manual_reference, :confirm_manual_processing, :manually_paid_at

validates :manually_paid_at, date: true
validates :manual_reference, length: { minimum: 6 }     

但是,提交表单时,出现以下错误:

Validation failed: Manually paid at is not a date, Manual reference is too short (minimum is 6 characters
Rails.root: /home/app

Application Trace | Framework Trace | Full Trace
app/models/invoice.rb:159:in `block in document_manual_payments_to_service_providers'
app/models/invoice.rb:155:in `each'
app/models/invoice.rb:155:in `document_manual_payments_to_service_providers'
app/controllers/admin/invoices_controller.rb:161:in `submit_for_payment'
app/middleware/catch_json_parse_errors.rb:8:in `call'

Request

Parameters:

{"utf8"=>"✓",
  "authenticity_token"=>"5De4XkSwxuu4xLPqgwtHmpoXQ1yBSDGTXDesAZeBmdg=",
  "invoices"=>["1535114522_188841_invoice"],
  "manually_paid_at"=>"01/27/2019",
  "manual_reference"=>"1234567",
  "confirm_manual_processing"=>"1",
  "commit"=>"Submit For Payment"}

从参数中可以看到,我正在提交有效的日期和有效的长度参考。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我看到了您在参数提交中的错误,即: "manually_paid_at"=>"01/27/2019"

所以这不是Date对象,这只是String对象,您必须将其转换为Date对象。

您可以使用to_date将其转换为Date对象

答案 1 :(得分:0)

  • 看来manually_paid_at是可以使用的无效日期 像下面这样在发送之前正确解析日期时间 进行建模

    DateTime.strptime("01/27/2019", "%m/%d/%y") => Mon, 27 Jan 2020 00:00:00 +0000

  • 对于手动参考来说太短(至少6个字符)我不是 确定为什么模型验证会添加该错误,因为"1234567"是有效的..我的猜测是参数值未发送到模型,因为"1234567"可能会检查您的代码,如果该参数值在某处被修改了您还可以执行以下操作来查看错误消息中的manual_reference的值:

    validates :manual_reference, length: { minimum: 6, message: "%{value} is invalid"}