轨道:fields_for选择
在我的视图中,我使用 fields_for 来显示关系表的表单数据。 然而,此表格的一部分将有可供选择的选择列表。 我看到 form_for 和 fields_for 帮助程序有 label、text_field、text_area 帮助程序,这些帮助程序将填充已填充的模型对象所需的信息......但是如果选择列表帮助程序可以执行相同的操作呢?
当我具有一对多关系时,这将特别有用,因为 fields_for 会迭代模型对象中已有的每个项目并使用索引显示它。
有这样的事情存在吗?
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?
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.
Does anything like this exist?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用多种选择帮助器方法。 最常见的是 collection_select。 如果您在模型上有一个
belongs_to
关联并且想要使用选择菜单来设置它,那么这非常有用。对于其他情况,有更通用的 select 方法。 您可以在此处提供一系列您想要提供的选项。
每个数组元素中的第一个值是选择选项的名称,第二个是将分配给属性的值。
还有许多其他选择菜单(用于日期和时间),但上述两个应该涵盖大多数情况。 这些方法适用于
form_for
或fields_for
。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.For other situations there is the more generic select method. Here you can supply an array of options you want to provide.
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.
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
orfields_for
.您正在寻找 select 或 collection_select。 两者都可以在 form_for 或 fields_for 块中使用。 文档中有关于如何在 form_for 中使用它们的示例
You are looking for select or collection_select. Both can be used in form_for or fields_for blocks. There are examples on how to use them in a form_for in the documentation