Rails 3 - how to save (un)checked checkboxes?

user984621 picture user984621 · Feb 23, 2012 · Viewed 8.8k times · Source

I have in a form (form_tag) several checkboxes like this:

<%=check_box_tag 'model_name[column_name]', 1, (@data.model_name.column_name == 1 ? true : false)%>

And updating them like:

variable = ModelName.find(params[:id])             
variable.update_attributes(params[:model_name])

This works only in a moment, when I check some checkboxes - send them and they will be saved. That's fine. But when I uncheck all checkboxes - send form - so nothing happend, in the DB table will not set the value 0 in the columns...

Could you give me any tip, how to fix it?

Thank you in advance

Answer

iblue picture iblue · Feb 23, 2012

This happens because an unchecked checkbox will not send any value to the server. To circumvent this Rails provides the check_box helper, which generates code like this:

<input type="hidden"   name="model[attr]" value="0" />
<input type="checkbox" name="model[attr]" value="1" />

Alternatively, insert a hidden field with hidden_field_tag:

<%= hidden_field_tag 'model_name[column_name]', '0' %>
<%= check_box_tag 'model_name[column_name]', 1, (@data.model_name.column_name == 1 ? true : false) %>