我想在用户编辑表单时显示我的下拉表单选定选项值。现在它显示第一个选项(在这种情况下是一个空白选项)。
表格
<%= f.select(:condition, options_for_select([["Brand New", "Brand New"], ["Pre-owned", "Pre-owned"]]), :include_blank => true, :selected => params[:condition]) %>
HTML输出
<select id="product_condition" name="product[condition]">
<option value=""></option>
<option value="Brand New">Brand New</option>
<option value="Pre-owned">Pre-owned</option>
</select>
JSON
{
id: 2,
condition: "Pre-owned",
}
感谢。
答案 0 :(得分:6)
<%= f.select(:condition, options_for_select([["Brand New", "Brand New"], ["Pre-owned", "Pre-owned"]], :selected => f.object.condition), :include_blank => true) %>
答案 1 :(得分:1)
检查options_for_select
文档,您会发现最后一个参数是所选选项。
options_for_select(container, selected = nil)
在你的情况下
<%= f.select(:condition, options_for_select([["Brand New", "Brand New"], ["Pre-owned", "Pre-owned"]], params[:condition]), :include_blank => true) %>
假设params[:condition]
包含当前选定的值,并且该值与select标记中的相应值匹配。
换句话说,要选择"Pre-owned"
,params[:condition]
必须包含"Pre-owned"
。
答案 2 :(得分:1)
此表单多个下拉列表,但用户只能选择一个,并且如果您编辑和显示方法仅显示一个记录。
<%= form.label :Hobbies%>
<%= form.select(:hobbies, options_for_select(%w[cricket football hockey reading], :selected => form.object.hobbies )) %><br><br>
答案 3 :(得分:1)
<%= f.select :condition, options_for_select([["Brand New", "Brand New"], ["Pre-owned", "Pre-owned"]], f.object.condition), {:include_blank => true} %>