以下のコードで示すように、同じフォームのチェックボックスの値に基づいてActiveModelオブジェクトのフォーム値を検証しようとしています。 ボックスがチェックされている場合(true
ではなく1
が返されます)、order_number
のバリデーションは、フィールドが非アクティブ化されている(JSによって)ので、無効にする必要があります。チェックボックスnot_a_customer
に接続されている属性を使用して、order_number
の妥当性検査の条件として以下の単純なアプローチが機能しませんでした。Rails 5:ActiveModelの条件付き検証を実装する方法は?
他に何を試すことができますか?
私は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')
上記のコードを試してみるとどのようなエラーが表示されますか? –
エラーはありません、私はそれが欲しいと検証していません。私はorder_numberを空白のままにして、ボックスをチェックしないでおくことができます。チェックボックスをオンにした場合のみ、注文番号が空白のままにすることが可能です。 – Flip
私はそれを正しく理解していれば、チェックボックスがチェックされていない場合のみ、検証が実行されます。右? –