html - rails select_tag, how to generate dropdown list with json value and custom text from an array -
i'ved got json array , want create dropdown selection list. , because json, dont want display json based on readable name.
i tried 2 methods came closest, cant want.
controller:
@books = [{"code"=>"pa1","name"=>"james","type"=>"novel"},{"code"=>"pa2","name"=>"john","type"=>"science"}]
method 1
form.html.erb:
<%= select "book", "book", @books.each_with_index.map {|name, index| [name,name["name"]]} %>
the generated html:
<select id="book_book" name="book[book]"><option code="pa1" name="james" type="novel" value="james">james</option> <option code="pa2" name="john" type="science" value="john">john</option></select></div>
method 2
form.html.erb:
<%= select_tag "book", options_for_select(@books) %>
the generated html:
<select id="book" name="book"><option value="{"code"=>"pa1","name"=>"james", "type"=>"novel"}">{"code"=>"pa1", "name"=>"james", "type"=>"novel"}</option><option value="{"code"=>"pa2", "name"=>"john", "type"=>"science"}">{"code"=>"pa2", "name"=>"john", "type"=>"science"}</option></select> </div>
method 3 (update new method not working well)
even not work, there 2 different "value"! getting more frustrated.
@books = [{"value" => {"code"=>"pa1","name"=>"james","type"=>"novel"}},{"value" => {"code"=>"pa2","name"=>"john","type"=>"science"}}] <%= select "book", "book", @books.each_with_index.map {|value, index| [value,value["value"]["name"]]} %></div> <select id="book_book" name="book[book]"><option value="james" value="{"code"=>"pa1", "name"=>"james", "type"=>"novel"}">james</option> <option value="john" value="{"code"=>"pa2", "name"=>"john", "type"=>"science"}">john</option></select></div>
this desired result want, please help!:
<select id="book_book" name="book[book]"><option value="{"code"=>"pa1","name"=>"james","type"=>"novel"}">james</option> <option value="{"code"=>"pa2","name"=>"john","type"=>"science"}">john</option></select></div>
i don't know why wanna pass whole hash string in value of <option>
if want generate this
<select id="book_book" name="book[book]"><option value="{"code"=>"pa1","name"=>"james","type"=>"novel"}">james</option> <option value="{"code"=>"pa2","name"=>"john","type"=>"science"}">john</option></select></div>
then should write following
<%= select("book", "book", @books.each.map {|hash| [hash['name'], hash.to_s] }) %></div>
Comments
Post a Comment