编辑表单时显示所选选项(Rails 4)

我想在用户编辑表单时显示我的下拉表单选定选项值。 现在它显示第一个选项(在这种情况下是一个空白选项)。

形成

 true, :selected => params[:condition]) %> 

HTML输出

   Brand New Pre-owned  

JSON

 { id: 2, condition: "Pre-owned", } 

谢谢。

 <%= f.select(:condition, options_for_select([["Brand New", "Brand New"], ["Pre-owned", "Pre-owned"]], :selected => f.object.condition), :include_blank => true) %> 

检查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"