Rails form (select/option) - how to mark selected option with HAML?

user984621 picture user984621 · Oct 2, 2012 · Viewed 28.6k times · Source

What's the quickest and most elegant way to mark currently selected option value in the form in HAML?

%form{:action => '', :method => 'get'}
   %select{:name => 'param_name'}
      %option{:value => 'A'} A data
      %option{:value => 'B'} B data

One way:

- if params[:param_name] == "A"
  %option{:value => 'A', :selected => 'selected'} A data
- else
  %option{:value => 'A'} A data

but this is inappropriate when the select box will has many option fields...

Answer

egze picture egze · Oct 2, 2012

Something like this will work (using the older "hashrocket syntax" with the operator =>)

%select
  %option{:value => "a", :selected => params[:x] == "a"}= "a"
  %option{:value => "b", :selected => params[:x] == "b"}= "b"

Or, in newer Ruby versions (1.9 and greater):

%select
  %option{value: "a", selected: params[:x] == "a"}= "a"
  %option{value: "b", selected: params[:x] == "b"}= "b"