A collection of computer systems and programming tips that you may find useful.
Brought to you by Craic Computing LLC, a bioinformatics consulting company.

Monday, February 15, 2010

Rails check_box_tag and Rails 2.3.x

Basic HTML checkboxes have an inherent problem in that there is no explicit value passed to the server when the box is unchecked.

Under Rails 2.2.2 (and thereabouts) you could circumvent this limitation with an ugly hack.

If you wanted to use a check_box_tag helper in a form you had to use a had to follow it with a hidden_field_tag that contained the unchecked value. For instance:

<%= check_box_tag :approval_check_box, '1' %>
<%= hidden_field_tag :approval_check_box, '0' %>

If the check box was not checked then value in the hidden field would be passed. Ugly, but it worked fine.

But at some point in the move to Rails 2.3.x this hack was turned on its head and the construct show above will now always pass the unchecked value to the server.

The fix is simple - just reverse the two lines:
<%= hidden_field_tag :approval_check_box, '0' %>
<%= check_box_tag :approval_check_box, '1' %>

The real solution if to use a check_box helper where you can explicitly specify the unchecked value, rather than a check_box_tag.

I stumbled across this while updating an older app from Rails 2.2.2 to 2.3.5. It took a while to narrow the issue down to this problem.


No comments:

Archive of Tips