Ruby-on-rails 如何使 f.select rails 被选中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18100834/
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 make the f.select rails selected
提问by Wayne Chu
It's my code:
这是我的代码:
<%= f.select :area, options_for_select([['a','a'],['b','b'],['c','c']]), {}, {:class => 'span3 controls controls-row'}, :selected => params[:area] %>
and result is:
结果是:
ArgumentError in Users#edit
Showing /home/airson/rails_projects/friends_of_local/app/views/users/edit.html.erb where line #17 raised:
wrong number of arguments (5 for 4)
why.....@@?
为什么.....@@?
回答by Raindal
No need to use :selectedjust pass your params[:area]alone to options_for_select as a second argument:
无需:selected将您params[:area]单独传递给 options_for_select 作为第二个参数:
<%= f.select :area,
options_for_select([['a','a'],['b','b'],['c','c']], params[:area]),
{}, { :class => 'span3 controls controls-row' } %>
The last value of your params[:area]will be selected.
params[:area]将选择您的最后一个值。
Hope it helps ; )
希望能帮助到你 ; )
回答by Marek Lipka
You should pass :selectedoption to options_for_selectmethod, like this:
您应该将:selected选项传递给options_for_select方法,如下所示:
<%= f.select :area, options_for_select([['a','a'],['b','b'],['c','c']], :selected => params[:area]), {}, { :class => 'span3 controls controls-row' } %>
回答by mayorsanmayor
The above answers didn't work for me on Rails 6. This is what worked. Copied from one of the answers on Reddit
以上答案在 Rails 6 上对我不起作用。这是有效的。复制自 Reddit 上的一个答案
= f.select(:results, options_for_select(['Accepted', 'Not Accepted', 'Rejected', 'Acc', 'Rej', 'Information Only', 'N/A'], selected: @report.results || nil), { include_blank: "Select Result" }, { class: 'form-control select2', style: 'width: 100%;'})

