options_from_collection_for_select定义

时间:2012-11-09 10:29:10

标签: ruby-on-rails-3

我刚刚阅读了option_from_collection_for_select的Rails API定义。

 Returns a string of option tags that have been compiled by iterating over the collection   and assigning the result of a call to the value_method as the option value and the text_method as the option text

现在我对rails非常陌生,所以想知道是否有人可以把它分解成更小的块并解释发生了什么,如果你愿意的话会愚蠢的,解释是非常高的水平(对我来说很好)< / p>

谢谢

1 个答案:

答案 0 :(得分:4)

使用Ruby on Rails API中的示例,我们假设您的Person模型具有id属性和name属性。

假设您有一个表单,可以创建新的project并将其分配给person。也许你想要一个下拉选择你正在为这个项目分配的person。你可以使用options_from_collection_for_select来做这样的事情。

<%= f.label :person, "Assigned Person" %>
<%= f.select(:person, options_from_collection_for_select(@people, "id", "name") )

(顺便说一下,f会在这里为我们的示例表单引用@project变量。)

这样做会在您的选择下拉列表中为实例变量person中包含的每个@people创建一个选项。每个<option>代码都会将id的{​​{1}}分配给其person属性,该选项的文本将为value person

因此,如果您的name变量包含@people,您将获得如下HTML输出:

[#<Person id: 1, name: "Brock Sampson">, #<Person id: 2, name: "Byron Orpheus">]

这更有意义吗?