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

1

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

Leff answered 22/2, 2012 at 23:59 Comment(0)
D
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) %>
Demission answered 23/2, 2012 at 0:10 Comment(2)
thanks, but the hidden input must be before the checkbox, in the sequence as you writing it doesn't works meLeff
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?Rora

© 2022 - 2024 — McMap. All rights reserved.