Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the check_box form helper generate two checkboxes, one hidden?

this code: =form_fo :store_products do |f| = f.check_box :track_inventory

creates this html:

<input name="product_group[products_attributes][0][store_products_attributes}[1342647745501][track_inventory]" type="hidden" value="0">

<input id="product_group_products_attributes_0_store_products_attributes_1342647745501_track_inventory" name="product_group[products_attributes][0][store_products_attributes][1342647745501][track_inventory]" type="checkbox" value="1">

What is the reason for the first hidden element?

like image 631
everett1992 Avatar asked Jul 18 '12 21:07

everett1992


1 Answers

The HTML specification says that unchecked checkboxes should not be sent by webbrowsers. This means that, if unchecked, rails receives no record of whether the checkbox on the form was unchecked. This would be important, for example, if the user was editing a record where the checkbox was previously checked and they had decided to uncheck it - rails would not know to update this attribute.

The hidden field has the same name as the checkbox, so if the checkbox is not sent, the hidden_field is sent instead (with the value of '0', meaning unchecked). This way, rails will always receive a signal as to whether the checkbox was checked or unchecked.

More information on this gotcha at APIDock

like image 87
Rob d'Apice Avatar answered Sep 19 '22 19:09

Rob d'Apice