Rails - 从对象哈希创建选择标签 [英] Rails - Creating a select tag from a object hash

查看:29
本文介绍了Rails - 从对象哈希创建选择标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

正如 Schrockwell 所说:

Just as Schrockwell has said:

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

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

<%= 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) %>

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

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

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

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')) %>

其中2"是所需选择的索引

where '2' is the index of the desired selection

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

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

这篇关于Rails - 从对象哈希创建选择标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆