Ruby-on-rails 如何在rails中正确使用单选按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15060268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use radio button correctly in rails?
提问by GiH
I'm trying to create some radio buttons and I'm not sure how to. Following thisquestion I've got it set up working almost correct, but I'm new to this and not sure why I can't figure it out completely. So what I'm doing is putting a label to group the boolean and then have radio buttons which are labeled Yes and No. If the user clicks the label of Yes it should select the radio button yes (right now they can only click the button itself). This is my code as follows:
我正在尝试创建一些单选按钮,但不知道该怎么做。按照这个问题,我已经把它设置得几乎正确,但我是新手,不知道为什么我不能完全弄清楚。所以我正在做的是放置一个标签来分组布尔值,然后有标记为是和否的单选按钮。如果用户单击是的标签,它应该选择单选按钮是(现在他们只能单击按钮本身)。这是我的代码如下:
<div class="field">
<%= f.label :autolyse %><br />
<%= f.label :autolyse, "Yes", :value => "Yes" %>
<%= f.radio_button :autolyse, true%>
<%= f.label :autolyse, "No", :value => "No" %>
<%= f.radio_button :autolyse, false, :checked => true %>
</div>
The first label is for the group, it labels the group "Autolyse". Then I want a Label for "Yes", which if selected will will set true, and then obviously the next one is for False. How do I get this set up correctly?
第一个标签用于组,它将组标记为“Autolyse”。然后我想要一个“是”的标签,如果选择它将设置为真,然后显然下一个是假的。我该如何正确设置?
回答by shweta
see label(object_name, method, content_or_options = nil, options = nil, &block)
见标签(object_name,方法,content_or_options = nil,options = nil,&block)
<div class="field">
<%= f.label :autolyse %><br />
<%= f.label :autolyse, "Yes", :value => "true" %>
<%= f.radio_button :autolyse, true %>
<%= f.label :autolyse, "No", :value => "false" %>
<%= f.radio_button :autolyse, false, :checked => true %>
</div>
回答by Carlos Castillo
If you want to keep selected the option chosen by the user, you should validate the param, would be something like this:
如果要保持选择用户选择的选项,则应验证参数,如下所示:
<div class="field">
<%= f.label :autolyse %><br />
<%= f.label :autolyse, "Yes", :value => "true" %>
<%= f.radio_button :autolyse, true, !!params[:autolyse] %>
<%= f.label :autolyse, "No", :value => "false" %>
<%= f.radio_button :autolyse, false, !!params[:autolyse] %>
</div>
If you want to do it from the object properties you just replace the params variable for the object property:
如果要从对象属性执行此操作,只需替换对象属性的 params 变量:
<div class="field">
<%= f.label :autolyse %><br />
<%= f.label :autolyse, "Yes", :value => "true" %>
<%= f.radio_button :autolyse, true, [email protected] %>
<%= f.label :autolyse, "No", :value => "false" %>
<%= f.radio_button :autolyse, false, [email protected] %>
</div>

