Creating Checkboxes

Checkboxes are mostly simple. They can be checked or not checked, and Rails maps their contents to a boolean value transparently. This simple request for a checkbox:

<%= f.check_box :can_send_email %>

yields this bit of HTML:

<input id="person_can_send_email" name="person[can_send_email]" type="checkbox"
value="1" /><input name="person[can_send_email]" type="hidden" value="0" />

That’s a little more complicated than expected, though. Why is there a second input element of type hidden? It’s another Rails workaround, providing a default value in case the checkbox isn’t checked:

Since HTTP standards say that unchecked checkboxes don’t post anything, we add a hidden value with the same name as the checkbox as a workaround.[1]

If the checkbox is checked, that value will go through. If not, the value of the hidden input with the same name will go through.

The check_box method has a few more tricks to offer. As was possible with the text fields, you can specify additional attributes—perhaps class for CSS styling?—with named parameters:

<%= f.check_box :can_send_email, :class => 'email' %>

This will produce a checkbox with a class attribute:

<input class="email" id="person_can_send_email" name="person[can_send_email]"
type="checkbox" value="1" /><input name="person[can_send_email]" type="hidden"
value="0" />

You can also specify that the box should be checked if you want, which will override the value that comes into the form from the underlying object. Use this with ...

Get Learning Rails now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.