本文介绍了如何设置form_for select的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何在form_for select上设置默认值.
I would like to know how to set default value on form_for select.
我的代码如下:
<%= form_for(@user) do |f| %>
.
.
.
<div class="field">
<%= f.select(:user_group_id, options_for_select(@user_groups.collect {|p| [ p.name, p.id ] }, "Select Category")) %>
</div>
<%= end %>
显然,它将返回字段user_group的所有值.在我的编辑页面上,我想将默认值设置为用户在user_group中具有的任何值.请帮助
Obviously it would return all the values of the field user_group. On my edit page, I would like to set the default value to whatever value the user have in the user_group. Pls help
推荐答案
您可以将第二个选项传递给options_for_select
,该选项指示所选的值.
You can pass a second option to options_for_select
that indicates the selected value.
options_for_select(@user_groups.collect { |p| [p.name, p.id] }, @user.user_group)
很明显,我不确定如何设置模型,但如有必要,可以使用查找以找到所需的条目.
Obviously I'm not sure how your models are set up, but if necessary you use a method like find to locate the entry you want.
这篇关于如何设置form_for select的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!