问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/11550941/why-does-the-check-box-form-helper-generate-two-checkboxes-one-hidden