Adnan
Adnan

Reputation: 26350

Show data from a hash-table into a select box

A have a hash-table with countries in it like this:

@countries = {'United States' => 'US', 'France' => 'FR'} 

and I use the following code to display it in a select box:

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

Now when it saves data in my table I got in my row US, UK...and so on, now the problem is when I want to output data, so instead of US I would like to output 'United States' I use:

<%=h @countries[@offer.from_country] %>

But the first hash-table cannot work and I have to reverse the order and use:

@countries = {'US' => 'United States', 'FR' => 'France'} 

Any ideas on how to have the same hash-table for both displaying the data in the select box, and then on the show page?

Upvotes: 0

Views: 624

Answers (3)

James
James

Reputation: 101

You can also do this with an array instead of a hash. This has the advantage that your options will always display in the sequence you place them in your array.

@countries = [['United States', 'US'], ['France', 'FR']]

Then your select_tag uses the array:

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

And to output the data you can use Array#rassoc:

<%=h @countries.rassoc(@offer.from_country)[0] %>

Upvotes: 2

klew
klew

Reputation: 14967

Use invert on your hash. It exchanges keys and values:

{:a => '1', :b => '2'}.invert
=> {"1"=>:a, "2"=>:b}

Your example:

<%=h @countries.invert[@offer.from_country] %>

Upvotes: 1

Veger
Veger

Reputation: 37905

Try to set the value attribute of the <option> tag to the short country names and the text between the tags to the full country names as shown in the FormOptionsHelper documentation.

Then the returned value is the short country name, but the user sees the full name in the menu.

Upvotes: 2

Related Questions