有人可以用清晰简单的术语向我解释collection_select吗?

mar*_*ion 135 ruby-on-rails ruby-on-rails-3

我正在浏览Rails API文档collection_select,它们太可怕了.

标题是这样的:

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

这是他们提供的唯一示例代码:

collection_select(:post, :author_id, Author.all, :id, :name_with_initial, :prompt => true)

有人可以解释一下,使用一个简单的关联(比如一个Userhas_many Plans,一个Plan属于一个User),我想在语法中使用什么,为什么?

编辑1:此外,如果你在一个form_helper或一个常规形式内解释它是如何工作的,那将是很棒的.想象一下,您正在向了解Web开发的Web开发人员解释这一点,但对Rails来说是"相对较新的".你会如何解释它?

ale*_*xkv 285

collection_select(
    :post, # field namespace 
    :author_id, # field name
    # result of these two params will be: <select name="post[author_id]">...

    # then you should specify some collection or array of rows.
    # It can be Author.where(..).order(..) or something like that. 
    # In your example it is:
    Author.all, 

    # then you should specify methods for generating options
    :id, # this is name of method that will be called for every row, result will be set as key
    :name_with_initial, # this is name of method that will be called for every row, result will be set as value

    # as a result, every option will be generated by the following rule: 
    # <option value=#{author.id}>#{author.name_with_initial}</option>
    # 'author' is an element in the collection or array

    :prompt => true # then you can specify some params. You can find them in the docs.
)
Run Code Online (Sandbox Code Playgroud)

或者您的示例可以表示为以下代码:

<select name="post[author_id]">
    <% Author.all.each do |author| %>
        <option value="<%= author.id %>"><%= author.name_with_initial %></option>
    <% end %>
</select>
Run Code Online (Sandbox Code Playgroud)

这没有记录在FormBuilder,但在FormOptionsHelper

  • 这很容易,是我见过的复杂Rails结构的最佳解释之一.您使用了清晰的语言,以及基本的Rails构造来巩固它.非常感谢!! (31认同)
  • 你为什么要把它命名为"post [author_id]"? (2认同)

zsq*_*are 20

我自己花了很多时间在select标签的排列上.

collection_select从对象集合中构建选择标记.记住这一点,

object:对象的名称.这用于生成标记的名称,用于生成选定的值.这可以是实际对象或符号 - 在后一种情况下,在绑定中查找ActionController该名称的实例变量(即:post查找@post控制器中调用的实例var ).

method:方法的名称.这用于生成标记的名称.换句话说,您尝试从选择中获取的对象的属性

collection :对象的集合

value_method :对于集合中的每个对象,此方法用于值

text_method :对于集合中的每个对象,此方法用于显示文本

可选参数:

options:您可以传递的选项.这些记录选项标题下.

html_options:无论在这里传递什么,只需添加到生成的html标记中.如果你想提供一个类,id或任何其他属性,它就在这里.

您的关联可以写成:

collection_select(:user, :plan_ids, Plan.all, :id, :name, {:prompt => true, :multiple=>true })

关于form_for再次以非常简单的术语使用所有标签form_for,例如,f.text_field,你不需要提供first(object)参数.这取自form_for语法.

  • 由于marcamillion如此清楚地说明的原因,我投了赞成票. (3认同)
  • 感谢您抽出时间......但唯一的问题是,老实说,您的解释无助于澄清我的想法.您在实际定义中使用了很多术语.我很感激你花时间 - 所以为此,我投了赞成票. (2认同)