12

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

user984621
  • 46,344
  • 73
  • 224
  • 412

1 Answers1

23

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) %>
user664833
  • 18,397
  • 19
  • 91
  • 140
iblue
  • 29,609
  • 19
  • 89
  • 128
  • 1
    thanks, but the hidden input must be before the checkbox, in the sequence as you writing it doesn't works me – user984621 Feb 23 '12 at 11:10
  • This method works, but for me I have `<%= hidden_field_tag 'model_name[column_name]' %>` and it stores an empty set of quotes at the beginning of the array... How do I get rid of the extra empty quotes? – Gcap Sep 29 '15 at 20:52