简体   繁体   中英

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.

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)%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM