rails:fields_for选择 [英] rails: fields_for select

查看:92
本文介绍了rails:fields_for选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,我正在使用fields_for显示关系表的表单数据.但是,此表单的一部分将具有选择列表供您选择.我看到有用于form_for和fields_for帮助器的label,text_field,text_area帮助器,它们将从已填充的模型对象中填充所需的信息...但是,选择列表帮助器会做同样的事情吗?

In a view that I have, I am using fields_for to display form data for a relational table. However, part of this form will have select lists to choose from. I see there are label, text_field, text_area helpers for the form_for and fields_for helpers that will fill in the info needed from an already populated model object... but what about a select list helper that will do the same?

当我与一对多关系时,这是特别有用的,因为fields_for会遍历模型对象中已经存在的每个项目并用索引显示它.

This would be particularly useful for when I have a one-to-many relationship since fields_for iterates through each item that is already in the model object and displays it with an index.

这样的东西存在吗?

推荐答案

可以使用几种选择帮助器方法.最常见的是 collection_select .如果您在模型上具有belongs_to关联,并且想要使用选择菜单进行设置,则非常好.

There are several select helper methods which you can use. The most common being collection_select. This is great if you have a belongs_to association on the model and you want to use a select menu to set this.

<%= f.collection_select :category_id, Category.all, :id, :name %>

对于其他情况,还有更通用的选择方法.在这里,您可以提供要提供的一系列选项.

For other situations there is the more generic select method. Here you can supply an array of options you want to provide.

<%= f.select :priority, [["Low", 1], ["Medium", 2], ["High", 3]] %>

每个数组元素中的第一个值是选择选项的名称,第二个是将分配给该属性的值.

The first value in each array element is the name of the select option, the second is the value which will be assigned to the attribute.

还有许多其他选择菜单(用于日期和时间),但以上两个应涵盖大多数情况.这些方法在form_forfields_for上均可使用.

There are many other select menus (for dates and times) but the above two should cover most situations. These methods work on both form_for or fields_for.

这篇关于rails:fields_for选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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