如何使用散列数组填充 select_tag? [英] How to populate a select_tag with an array of hashes?
问题描述
在 Rails 3.2 应用程序中,我尝试添加一个选择字段,该字段从外部 API 调用中获取其数据.此数据作为散列数组返回:
In a Rails 3.2 app I'm trying to add a select field that takes its data from an external API call. This data is returned as an array of hashes:
[{"name"=>"NameA", "id"=>"001"}, {"name"=>"NameB", "id"=>"002"}]
我如何使用这些数据来构建一个类似于以下内容的选择字段:
How can I use this data to construct a select field that looks something like:
<select>
<option value="001"> NameA </option>
<option value="002"> NameB </option>
</select>
感谢以下建议,我尝试了以下操作:
Thanks to the suggestions below I've tried the following:
答:
<%= select_tag 'model[field]', options_from_collection_for_select(@hash, :id, :name) %>
给出错误:
undefined method `name' for {"name"=>"NameA", "id"=>"001"}:Hash
乙:
<%= select_tag 'model[field]', options_from_collection_for_select(@hash) %>
修复了错误但生成了错误的标记
Fixes the error but generates the wrong markup
<option value="{"name"=>"NameA", "id"=>"001"}"> {"name"=>"NameA", "id"=>"001"}</option>
所以我认为我的问题是正确格式化散列数组,而我对操作散列数组知之甚少,无法弄清楚如何做到这一点.
So I think my problem is formatting the array of hashes correctly, and I don't know enough about manipulating arrays of hashes to work out how to do this.
除非我完全看破旧的方向,否则我认为这个问题的关键是重新格式化这个问题顶部的数组以给出:
Unless I'm looking in completly the worng direction, I think the key to this problem is to reformat the array at the top of this question to give:
{"NameA" =>"001", "NameB" =>"002"}
这甚至可能吗?如果是这样,如何?
Is this even possible? And if so, how?
推荐答案
一个更好的方法,只需一个命令:
A better way to do it in only one command:
<%= select_tag "model[field]", options_for_select(@array_of_hashes.map { |obj| [obj['name'], obj['id']] }) %>
使用您的示例哈希:
irb> @array_of_hashes = [{"name"=>"NameA", "id"=>"001"}, {"name"=>"NameB", "id"=>"002"}]
=> [{"name"=>"NameA", "id"=>"001"}, {"name"=>"NameB", "id"=>"002"}]
irb> @array_of_hashes.map { |obj| [obj['name'], obj['id']] }
=> [["NameA", "001"], ["NameB", "002"]]
这篇关于如何使用散列数组填充 select_tag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!