Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 313
user984621 Avatar asked Feb 22 '12 23:02

user984621


1 Answers

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) %>
like image 130
iblue Avatar answered Oct 20 '22 00:10

iblue