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

左心房为你撑大大i 提交于 2019-12-03 07:30:03

问题


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


回答1:


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) %>


来源:https://stackoverflow.com/questions/9405189/rails-3-how-to-save-unchecked-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!