Search code examples
ruby-on-railssimple-formmodelattribute

rails 4 simple form include_blank still sending empty attributes


I have the following form setup:

= simple_form_for(@job, url: job_payment_path, html: { id: 'payment-processor-form' }) do |j|
  div[class='row']
    div[class='col-md-12']
      div[class='panel panel-default']
        div[class='panel-heading']
          h3[class='panel-title']
            |Total Cost
        div[class='panel-body']
          h2[class='job-cost' data-initial = "#{job_base_price}"]
            = number_to_currency(job_base_price)
        div[class='panel-heading']
          h3[class='panel-title']
            |Have a coupon?
        div[class='panel-body']
          div[class='row-inline']
            div[class='row-block row-block-one']
              = j.simple_fields_for :coupon_attributes, @job.coupon do |c|
                = c.input_field :code, maxlength: 50, id: 'coupon-code', class: 'form-control', data: { 'initial' => 0 }, include_blank: false
            div[class='row-block']
              button[type='button' class='btn btn-primary' id='coupon-verify' ]
                |Verify
            p[class='help-hint']
              = t('simple_form.hints.coupon.code')

  div[class='row']
    div[class='col-md-12']
      = j.button :button, type: 'button', class: 'btn-primary text-uppercase', id: 'purchase-job' do
        = job_posting_button_step_label

When this form submits, I am seeing the following attributes:

enter image description here

This is not right.

I would expect the coupon code to be nil, not "".

Am I missing something here?


Solution

  • I see two things:

    first:
    :include_blank is an option for select fields, it skips the generation of a blank option tag at the beginning. code is an input field. If you want to force an input value, try required: true.

    second:
    form values are sent to the server as application/x-www-form-urlencoded. Empty imput fields are sent as i.e. job[coupon_attributes][code]=. There is no distinction between an empty string and no value.
    The convention in Rails is to interpret all input values as string (and typecast later when assigning values to models). So an empty value is always returned as ''.