Simple_form: why are two input tags generated instead of one?

Why does simple_form generate input tags twice for boolean fields (one is hidden and the other is not)?

In my simple_form, I have this:

<%= form.input :over_phone, as: :boolean, input_html: {checked: true} %>

which generates this:

 <div class="control-group boolean optional order_over_phone"> <label class="boolean optional control-label" for="order_over_phone">Order over phone</label> <div class="controls"> <input name="order[over_phone]" type="hidden" value="0"> <label class="checkbox"> <input checked="checked" class="boolean optional" id="order_over_phone" name="order[over_phone]" type="checkbox" value="1"> </label> </div> </div> 

As you can see, one input tag is hidden with a value of 0, and the other is invisible with a value of 1. If I submit a form, in the message parameters I get both values:

 order[over_phone]:0 order[over_phone]:1 

I have a random behavior when creating a model associated with this Boolean field, so I wonder if this is caused by simple_form. This does not happen with non-boolean field types.

If you encounter a similar problem, please share your experience.

I am using simple_form 2.1.0.

+7
ruby-on-rails simple-form form-helpers
source share
1 answer

check_box gotcha

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box

The HTML specification states that checkboxes with checkboxes were unsuccessful and therefore web browsers do not send them. Unfortunately, this introduces getcha: if the account model has a paid flag, and in the form that edits the paid account, the user unchecks the box, no paid parameter is sent. Thus, any hypostasis of mass appropriation, such as

 @invoice.update(params[:invoice]) 

will not update the flag.

To prevent this, the helper generates an auxiliary hidden field right up to the checkbox. the hidden field has the same name, and its attributes mimic the unchecked box.

Thus, the client sends only a hidden field (if unchecked) or both fields. Since the HTML specification indicates that key / value pairs should be sent in the same order, they appear on the form, and retrieving the parameters gets the last occurrence of any re-key in the query string, which works for regular forms.

+8
source share

All Articles