1

我有这个代码:

%tr
  %th Parent      
  %td
    %select{ :name => "firstlevel_id", :value => "#{@s.firstlevel_id}" }
      - Firstlevel.find(:all).each do |f|
        %option{ :value => "#{f.id}" } #{f.title}

但即使firstlevel_id它已经是选项列表中的 id 之一,它也不会显示为选中状态。

4

2 回答 2

2
  1. 您可以使用select_tag助手创建select标签和控制选定的值。
  2. 您还可以selected在适当的option标签上设置属性:

    %select{:name => "firstlevel_id"}
      - FirstLevel.find(:all).each do |f|
        %option{:value => f.id, :selected => f.id == @s.firstlevel_id} #{f.title}
    

我更喜欢第一个解决方案。

于 2013-09-18T16:09:31.867 回答
1

您应该使用 select_tag 生成 html ,并使用 options_for_select 生成 html :

select_tag :firstlevel_id, options_for_select( Firstlevel.all.map{|l| [l.title, l.id] }, @s.try(:firstlevel_id) )
于 2013-09-18T16:12:38.717 回答