<div class="col-md-10">
<%= f.radio_button :recipients, 'Resources', checked: true %> Resources<br />
<%= f.radio_button :recipients, 'Organisations', checked: true %> Organisations<br />
<br/>
</br/>
</div>
我的表单中有这个单选按钮,如果选择了“组织”,那么我希望表单能够将其传递给模型/控制器,然后收件人将成为组织。请帮助我还是Ruby的新手
答案 0 :(得分:1)
如果您正在使用form_for(@model_name)帮助程序,那么params [:model_name] [:recipients]将帮助您检索所需的值。
如果你使用form_tag helper,那么你可以使用params [:recipient]获得相同的值。
答案 1 :(得分:0)
好的,这是哈希:
{"utf8"=>"✓", "authenticity_token"=>"YzFNk2cSNWU5DarWw4B1dMJYDX4mc==",
"broadcast"=>{"subject"=>"Test email",
"message"=>"This is an organisation test email",
"recipients"=>"Organisations",
"country_id"=>"1", "skill_id"=>"", "id"=>["", "7", "5", "8"]}, "commit"=>"Send"}
Rails将哈希值分配给名为params
的变量:
params = {"utf8"=>"✓", "authenticity_token"=>"YzFNk2cSNWU5DarWw4B1dMJYDX4mc==",
"broadcast"=>{"subject"=>"Test email",
"message"=>"This is an organisation test email",
"recipients"=>"Organisations",
"country_id"=>"1", "skill_id"=>"", "id"=>["", "7", "5", "8"]}, "commit"=>"Send"}
虽然可能有点难以理解,但params["broadcast"]
具有以下值:
{
"subject"=>"Test email",
"message"=>"This is an organisation test email",
"recipients"=>"Organisations",
"country_id"=>"1",
"skill_id"=>"",
"id"=>["", "7", "5", "8"]
}
要将该哈希值转换为变量,您可以编写:
form_data = params["broadcast"]
这相当于:
form_data = {
"subject"=>"Test email",
"message"=>"This is an organisation test email",
"recipients"=>"Organisations",
"country_id"=>"1",
"skill_id"=>"",
"id"=>["", "7", "5", "8"]
}
该哈希包含表单中的所有键/值对。每个键对应于表单中某个输入字段的name属性,值是该输入字段的值。您应该查看浏览器中的Page Source
以检查表单创建的html。在html源代码中找到该表单,并检查每个输入字段的name属性。另外,请参阅Binding a form to an Object上的Rails指南,了解表单创建的html的一些示例。
最后,您可以在form_data
哈希中获取“收件人”键的值,如下所示:
if form_data["recipient"] == "Organisations"
...
...
end
由于form_data
等同于params["broadcast"]
,您可以在if语句中替换params["broadcast"]
代替form_data
,为您提供:
|<--form_data---->|
| |
if params["broadcast"]["recipient"] == "Organisations"
...
...
end