簡體   English   中英

Rails 5:如何為ActiveModel實施條件驗證?

[英]Rails 5: How to implement a conditional validation for an ActiveModel?

如下面的代碼所示,我正在嘗試根據相同表單復選框的值來驗證ActiveModel對象的表單值。 如果選中此框(我確定它將返回true而不是1 ), order_number應該停用對order_number的驗證,因為該字段也正在被停用(通過JS)。 如下所示,使用連接到復選框not_a_customer的屬性作為驗證order_number條件的幼稚方法不起作用。

我還能嘗試什么?

我有一個ActiveModel類:

class SupportCase
  include ActiveModel::Model
  include ActiveModel::Validations

  attr_accessor(:email, :os, :inquiry_type, :order_number, :first_name, :last_name, :message, :not_a_customer)

  validates :order_number, presence: true,
                           numericality: { only_integer: true },
                           length: { in: (4..5), message: 'doh' },
                           unless: :not_a_customer
end

以及用於創建支持案例的表格:

= simple_form_for @support_case, html: { class: 'form inset' } do |f|
  .row
    .col.sm-6
      .row{ id: 'order-row' }
        .col.sm-6
          = f.input :order_number, input_html: { class: 'icon-field hash-icon' }
        .col.sm-6
          .label-title{ title: t("simple_form.labels.support_case.hint") }
            = f.input :not_a_customer, as: :boolean do
              = f.check_box :not_a_customer, {}, "true", "false"

    .col.sm-6
      = f.input :email, input_html: { type: 'email', required: 'true' }
      = f.input :first_name, input_html: { type: 'text' }
      = f.input :last_name, input_html: { type: 'text' }

    .col.sm-12
      ~ f.input :message, as: 'text', input_html: { required: 'true' }

    %button.btn.btn-action
      = t('views.contact.form.submit')

檢查not_a_customer的值。 您只是得到一個字符串,而不是布爾值,該值始終是真實的(“ true”,“ false”都是真實值)。

在Rails中,您可以not_a_customer.to_bool將其轉換為布爾值。

checkbox不會將您的值轉換為boolean ,因為params被解析為好像都是字符串(包括intstringboolean值)一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM