Ruby-on-rails rails,simple_form,如何在页面加载时设置集合的选定索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9107751/
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
rails, simple_form, how to set selected index of a collection when page loaded?
提问by simo
I am using simple_form gem, I have a countries collection, it work fine when I select the country, and updated record will have the country id stored, but, when I try to edit the record, the chosen country is not selected by default at edit form.
我正在使用 simple_form gem,我有一个国家集合,当我选择国家时它工作正常,更新的记录将存储国家 ID,但是,当我尝试编辑记录时,默认情况下未选择所选国家编辑表格。
Here is the code at edit form:
这是编辑表单中的代码:
= f.input :country_id, :collection => all_countries
Shouldn't simple_form view the selected country from the db ?
simple_form 不应该从 db 中查看选定的国家吗?
回答by Manish Shrivastava
Have you tried to use the :selected => option?
您是否尝试过使用 :selected => 选项?
:selected => selected_country_id
So,
所以,
= f.input :country_id, :collection => all_countries, :selected => selected_country_id
This will work perfectly !!!
这将完美地工作!!!
Cheers!
干杯!
回答by genkilabs
I know this has been answered, but I came here looking for a similar solution for a collection of check boxes. For posterity, here's how you do it:
我知道这已经得到了回答,但我来到这里是为一组复选框寻找类似的解决方案。对于后代,这是您的方法:
<%= f.input :country_ids, :as => :check_boxes, :collection => [['USA', :USA], ['Japan', :JPN]], :checked => [:JPN], :include_hidden => false %>
Hope this helps someone.
希望这可以帮助某人。

