Rails 3 - 如何保存(取消)选中的复选框? [英] Rails 3 - how to save (un)checked checkboxes?

查看:19
本文介绍了Rails 3 - 如何保存(取消)选中的复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个表单 (form_tag) 中有几个这样的复选框:

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

并像这样更新它们:

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

这只是片刻,当我选中一些复选框时 - 发送它们,它们将被保存.没关系.但是当我取消选中所有复选框时 - 发送表单 - 所以什么也没发生,在数据库表中不会在列中设置值 0...

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?

提前致谢

推荐答案

发生这种情况是因为未选中的复选框不会向服务器发送任何值.为了规避这个 Rails 提供了 check_boxhelper,它生成这样的代码:

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" />

或者,插入一个带有 hidden_​​field_tag 的隐藏字段:

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

这篇关于Rails 3 - 如何保存(取消)选中的复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆