views:

82

answers:

1

Hello,

I am new in Rails and I am trying to put countries in array and then display them in a select box. My array looks like this:

country = {}
country['FR'] = 'France'
country['UK'] = 'United Kingdom'

Any ideas?

+3  A: 

In your view, do the following :

<%= select_tag 'countries', 
            options_for_select(@countries.to_a) %>

The @countries.to_a will transform your hash into a array. If your hash is the following :

{'France' => 'FR', 'United Kingdom' => 'UK'}

After, after to_a you'll have the following array :

[['France', 'FR'], ['United Kingdom', 'UK']]

The options_for_select method takes an array and create the options tags.
When the entry of the array is an array itself, the first entry (France or United Kingdom here) is the value. And the second one is the key (FR or UK here).

The select_tag function creates a select tag.

Damien MATHIEU
Thank you: after setting @countries = {'France' => 'FR', 'United Kingdom' => 'UK'} it works
Adnan
Oh indeed my bad. It's the opposite. The first is the value and then comes the id.
Damien MATHIEU