Rails: 慎用 f.check_box , 推荐使用 check_box_tag ( prefer to use check_box_tag or hash, but not f.checkbox in Rails)

访问量: 2364

TODO: 翻译成汉语 

Returns a checkbox tag tailored for accessing a specified attribute (identified by method) on an object assigned to the template (identified by object). This object must be an instance object (@object) and not a local object. It’s intended that method returns an integer and if that integer is above zero, then the checkbox is checked. Additional options on the input tag can be passed as a hash with options. The checked_value defaults to 1 while the default unchecked_value is set to 0 which is convenient for boolean values.


The HTML specification says unchecked check boxes are not successful, and thus web browsers do not send them. Unfortunately this introduces a gotcha: if an Invoice model has a paid flag, and in the form that edits a paid invoice the user unchecks its check box, no paid parameter is sent. So, any mass-assignment idiom like


wouldn’t update the flag.

To prevent this the helper generates an auxiliary hidden field before the very check box. The hidden field has the same name and its attributes mimic an unchecked check box.

This way, the client either sends only the hidden field (representing the check box is unchecked), or both fields. Since the HTML specification says key/value pairs have to be sent in the same order they appear in the form, and parameters extraction gets the last occurrence of any repeated key in the query string, that works for ordinary forms.

Unfortunately that workaround does not work when the check box goes within an array-like parameter, as in

  <%= fields_for "project[invoice_attributes][]", invoice, :index => nil do |form| %>
    <%= form.check_box :paid %>
  <% end %>

because parameter name repetition is precisely what Rails seeks to distinguish the elements of the array. For each item with a checked check box you get an extra ghost item with only that attribute, assigned to “0”.

In that case it is preferable to either use check_box_tag or to use hashes instead of arrays.


  # Let's say that @post.validated? is 1:
  check_box("post", "validated")
  # => <input name="post[validated]" type="hidden" value="0" />
  #    <input type="checkbox" id="post_validated" name="post[validated]" value="1" />

  # Let's say that @puppy.gooddog is "no":
  check_box("puppy", "gooddog", {}, "yes", "no")
  # => <input name="puppy[gooddog]" type="hidden" value="no" />
  #    <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />

  check_box("eula", "accepted", { :class => 'eula_check' }, "yes", "no")
  # => <input name="eula[accepted]" type="hidden" value="no" />
  #    <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />

订阅/RSS Feed