Green
Green

Reputation: 471

Populating Select Box with Hash Array in rails

Anyway I've created a Hash Array :

@example= ['A' => '1', 'B' => '2']

or Array

@example=[1,2]

here you've got the key (being the english name) and the value (the generic equivalent).

what I want to do is make a drop-down single-selection box use these key/value properties to render it correctly,

  <%= f.collection_select @example %>

...this doesn't work but what i'd like is generate the form code...

#from HASH
<select >
<option value="1">A</option>
<option value="2">B</option>
</select>

or

#from array
<select>
<option>1</option>
<option>2</option>
</select>

Any help really appreciated.

Upvotes: 1

Views: 3655

Answers (1)

Surya
Surya

Reputation: 16002

For:

@example = [["A", 1, {:class=>"bold"}], ["B", 2], ["C", 3]] # {:class=> "bold"} is optional, use only if you need html class for option tag.

Try:

<%= form_for @whatever do |f|%>
# some code here..
<%= f.select :example, options_for_select(@example) %>
# rest of the code..
<% end %>

Or you can use:

<%= form_for @whatever do |f|%>
# some code here..
<%= f.select :example, @example %> # I am guessing that maybe you can not pass hash here for option tag.
# rest of the code..
<% end %>

Without form_for:

<%= select_tag :example, @example %>
# or
<%= select_tag :example, options_for_select(@example)%>

Upvotes: 5

Related Questions