Rails: populate the selection list using the US states and abbreviation using Decoder :: Countries [: US] .states

Good evening.

I am trying to dynamically populate a select_tag call in my rail view using Decoder :: Countries to create a list. My problem is that I can’t get the options to exit in the format I need.

Syntax:

Decoder::Countries[:US] 

returns a hash of US states in the format:

 "AL" => "Alabama" 

So, in the view, do the following:

 select_tag :tag_name, options_for_select(Decoder::Countries[:US].states.sort) 

creates a selection list that looks like this:

 <select name="tag_name" id="tag_name"> <option value="Alaska">AK</option> <option value="Alabama">AL</option> etc... 

What I need is output as follows:

 <select name="tag_name" id="tag_name"> <option value="al">Alaska</option> 

Now I know that adding .sort turns the hash into an array. How can I get it to display the output I need, or do I need to somehow connect it to the controller?

Thanks.

+4
source share
1 answer

Does hash inversion work?

 select_tag :tag_name, options_for_select(Decoder::Countries[:US].states.invert) 
+4
source

Source: https://habr.com/ru/post/1335617/


All Articles