Ruby on rails and JSON to create Select form -
this question has answer here:
- rails select json array 1 answer
i want create form :
<select> <option> </select>
with ruby on rails, countries (and there lot of countries in world haha), don't want write on view, want put json file countries, , theme in option items ( each method maybe )
i don't know have put json file in rails app , how call in view,
does me ?
the easiest location put json file in same directory controllers -- although doing kind of thing repeatedly make mess out of controllers folder.
once you've done can read controller this:
file = file.read('./countries.json') countries = json.parse(file)
and map countries data type options_for_select
expects.
once have working, i'd recommend making helper knows how read json file, cache it's data, , return it. store json file in same directory helper. reference helper in controller.
also note: json gem required this.
in helper, want create method:
def countries_for_select file = file.read('./countries.json') countries = json.parse(file) countries.map {|c| [ c['country']['label'], v['country']['country_code'] ] }) end
.map
translates fields countries json object [[name,key], ...]
array options_for_select
expects.
per form helper on rails documentation, syntax select_tag
looks this
<%= select_tag(:country, options_for_select(...)) %>
but created helper countries_for_select
match format select_tag
expecting. need this:
<%= select_tag(:country, countries_for_select) %>
Comments
Post a Comment