Ruby-on-rails Rails - 从对象哈希创建选择标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/824857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:12:57  来源:igfitidea点击:

Rails - Creating a select tag from a object hash

ruby-on-rails

提问by Neil Middleton

I need to create a select box from the values available in a Hash.

我需要从哈希中可用的值中创建一个选择框。

For instance, I have a 'thing' and the 'thing' has a variety of status fields:

例如,我有一个“事物”,而“事物”有多种状态字段:

1 => 'State A'
2 => 'State B'

available via a method on thing.

可通过事物的方法获得。

How can I build a select tag from this?

如何从中构建选择标签?

回答by nasmorn

Just as Schrockwell has said:

正如施罗克韦尔所说:

Hash.each |a|returns an array of the form a = [key, value], so for the hash @status_fieldsyou can write:

Hash.each |a|返回形式a = [key, value]为 的数组,因此对于散列,@status_fields您可以编写:

<%= collection_select('thing', 'status', @status_fields, :first, :last) %>

Alternatively, if you'd like the key to show up in the select list and the value point to the select list value, then:

或者,如果您希望键显示在选择列表中并且值指向选择列表值,则:

<%= collection_select('thing', 'status', @status_fields, :last, :first) %>

This will select the option given by thing.status or nothing if nil is returned

这将选择 thing.status 给出的选项,如果返回 nil 则不选择

If you want to just create any selection not tied to an object use

如果您只想创建与对象无关的任何选择,请使用

<%= select_tag('name', options_from_collection_for_select(@status_fields, :first, :last, '2')) %>

where '2' is the index of the desired selection

其中“2”是所需选择的索引

PS: I don't have enough reputation to just amend the original post or comment on it

PS:我没有足够的声誉来修改原始帖子或对其发表评论

回答by cpjolicoeur

you could do something like

你可以做类似的事情

select "foo", "bar", @hash_object

or

或者

select "foo", "bar", @hash_object.map { |h| [h.key, h.value] }

I'd probably invert your hash first to make the key point to the value

我可能会先反转您的哈希值以使关键点指向值

回答by Pesto

The select helper methodwill accept a hash in the form { text_displayed_in_select => select_value }, so you'll probably want to invertthat hash.

选择辅助方法,将在形式接受一个哈希{ text_displayed_in_select => select_value },所以你可能会想反转散列。



回答by Schrockwell

Hash.each |a|returns an array of the form a = [key, value], so for the hash @status_fieldsyou can write:

Hash.each |a|返回形式a = [key, value]为 的数组,因此对于散列,@status_fields您可以编写:

<%= collection_select('thing', 'status', @status_fields, :first, :last) %>

Alternatively, if you'd like the key to show up in the select list and the value point to the select list value, then:

或者,如果您希望键显示在选择列表中并且值指向选择列表值,则:

<%= collection_select('thing', 'status', @status_fields, :last, :first) %>