I need to populate a dropdownlist in ruby on rails with the data in an xml document.
The xml document is formatted like so:
<Countries>
<Country>
<CountryCode>US</CountryCode>
<CountryName>United States</CountryName>
</Country>
...
</Countries>
I then tried to convert to a hash using this code:
<% countries_xml = File.read(".../countries.xml") %>
<% countries = Hash.from_xml(countries_xml) %>
And I got a hash like this:
{"Countries"=>{"Country"=>[{"CountryCode"=>"US", "CountryName"=>"United States"}, ... ]}}
And I’m trying to use this hash to populate the dropdownlist but I think I am stuck. I’ve tried like this:
<% user.select :country, countries["Countries"]["Country"].each %>
But this just fills the dropdownlist with hashes because the countries object is a hash of an array of hashes or something like that. I need it so that the CountryNames are in the dropdownlist and the CountryCodes are sent when the user posts the form.
Have a look at the documentation for the select form builder method here:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
Essentially you need to do this to build the array of options for the select:
Also, you’ll probably want to take that xml file read and parsing methods out of the view and pop it into the controller, or even into the model as a class method. It’ll help to keep your code more maintainable, but that’s just my two cents…