Carla Dessi
Carla Dessi

Reputation: 9666

Showing which option is selected in rails dropdown

I have this code:

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

but even if the firstlevel_id is already one of the id's in the options list, it doesn't show it as selected.

Upvotes: 1

Views: 4081

Answers (2)

MrYoshiji
MrYoshiji

Reputation: 54882

You should use the select_tag to generate the html , and options_for_select to generate the html :

select_tag :firstlevel_id, options_for_select( Firstlevel.all.map{|l| [l.title, l.id] }, @s.try(:firstlevel_id) )

Upvotes: 1

Jakub Kosiński
Jakub Kosiński

Reputation: 907

  1. You can use select_tag helper to create select tag and control selected value.
  2. You can also set selected attribute on proper option tag:

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

I would prefer the first solution.

Upvotes: 2

Related Questions