[英]Array of Hashes into dropdown in Rails
In Rails, I have an array of hashes (@things) that looks something like this: 在Rails中,我有一系列哈希(@things),看起来像这样:
[
{"id"=>1, "name"=>"firstThing"},
{"id"=>2, "name"=>"secondThing"},
{"id"=>3, "name"=>"thirdThing"}
]
I also have an object with a thingId with a value of 2 (@otherThing.thingId = 2). 我还有一个对象,其thingId的值为2(@ otherThing.thingId = 2)。 I would like to turn the array into a dropdown with an empty option and with the secondThing option selected (because it has id = 2).
我想将数组变成一个带有空选项并选择secondThing选项的下拉列表(因为它的id = 2)。
I successfully built this with some if, else
and using that to output some <option value...
code, then realized that's probably not the Railsy way to do it. 我成功地用
if, else
构造了if, else
并使用它来输出一些<option value...
代码,然后意识到这可能不是Railsy的实现方式。 Not sure exactly how to railsify this the best way. 不确定到底该如何用最好的方法来解决。 I have reviewed the documentation at http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html , but I'm not sure how my array of hashes fits in with all of that.
我已经查看了http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html上的文档,但是我不确定我的哈希数组如何适合所有这些。
The options_for_select
helper can take an array like this: options_for_select
帮助器可以采用如下数组:
[
["firstThing", "1"],
["secondThing", "2"],
["thirdThing", "3"]
]
(The select helper uses options_for_select internally, so, depending on your use case, it makes this even simplier) So all you need is to convert your array of hashes into the above form. (选择助手在内部使用options_for_select,因此,根据您的用例,它甚至会更简单)。因此,您所需要做的就是将哈希数组转换为上述形式。 For example like this:
例如这样:
arrayForOptions = arrayOfHashes.collect { |item|
[item['name'], item['id']]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.