[英]How to check if a check_box in simple_form has been checked
Here's the HTML that it produces 这是它产生的HTML
f.check_box :tos
produces 产生
<input name="user[tos]" type="hidden" value="0">
<input id="user_tos" name="user[tos]" type="checkbox" value="1">
What would I need to do in a controller to check if it's been checked? 我需要在控制器中做什么以检查是否已检查?
Assuming you mean you want to find out if it is checked upon submission , then you could get it's value via params[:user][:tos]
. 假设您想知道是否在提交时对其进行了检查,则可以通过
params[:user][:tos]
来获取它的值。 All submitted data from a form is stored in the params hash, and its location is equivalent to the name attribute of the input. 表单中所有提交的数据都存储在params哈希中,其位置等效于输入的name属性。 So for instance:
因此,例如:
if params[:user][:tos] == "1"
# Do whatever is here if checked
else
# Do whatever is here if unchecked
end
If you need to react to its state of being checked on a web page, this cannot be done by the controller, and must use JavaScript. 如果您需要对在网页上被检查的状态做出反应,则控制器无法完成此操作,必须使用JavaScript。 Something like:
就像是:
if (document.getElementById('user_tos').checked == 1){
// Do whatever is here if checked
} else {
// Do whatever is here if unchecked
}
Addendum 附录
When receiving a parameter via your controller, don't use that value to create a new object (ie Thing.create( thing_value: params[:user][:tos] )
). 通过控制器接收参数时,请勿使用该值创建新对象(即
Thing.create( thing_value: params[:user][:tos] )
)。 If this is y our goal, you should look into "strong parameters," and how Rails implements them. 如果这是我们的目标,则应研究“强参数”,以及Rails如何实现它们。
Addendum 2 附录2
Thanks to ruby's duck typing (dynamic typing) and the nature of the params Hash, url encoding, etc. Integers sent via params, in this case params[:user][:tos]
, will get mutated to String . 感谢ruby的duck类型(动态类型)以及params的性质Hash,url编码等。通过params发送的整数(在本例中为
params[:user][:tos]
)将被变异为String 。 So you'll need to check for "1" (the string form) not 1 (the int form). 因此,您需要检查“ 1”(字符串形式)而不是1(int形式)。
In th controller, all parameters are delivered in the hash params
. 在次控制器,所有参数都在哈希交付
params
。 Your params
will have a key user
with the hash of all user input fields. 您的
params
将具有一个关键user
,该user
具有所有用户输入字段的哈希值。
The hidden field, that simple_form insterts before the checkbox ensures that params[:user][:tos]
is set (with value 0) even when the checkbox is not set. 即使未选中该复选框,simple_form在复选框之前插入的隐藏字段也可以确保已设置
params[:user][:tos]
(值为0)。
So you can check 所以你可以检查
if params[:user][:tos]>0
# your stuff
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.