Flip
Flip

Reputation: 6761

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

As the code below shows, I am trying to validate an form value of an ActiveModel object based on the value of a checkbox of the same form. If the box is checked (I made sure it will return true not 1) the validation on order_number should be deactivated, as the field is being deactivated as well (by JS). The naive approach shown below, using the attribute that is connected to the checkbox not_a_customer as conditional for the validation of order_number didn't work.

What else can I try?

I have an ActiveModel class:

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

And a form for creating support cases:

= 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')

Upvotes: 0

Views: 421

Answers (1)

Edmund Lee
Edmund Lee

Reputation: 2574

Check the value of not_a_customer. You are just getting a string instead of a boolean value, which is always truthy ("true", "false" are both truthy value).

In Rails, you can do not_a_customer.to_bool to convert it into boolean.

The checkbox does not convert your value into boolean, because params is parsed as if they are all strings (including int, string, boolean values).

Upvotes: 1

Related Questions