有人可以清楚,简单地向我解释collection_select吗?
我正在浏览collection_select的Rails API文档,它们是非常糟糕的。
标题是这样的:
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)
有人可以解释,使用一个简单的关联(比如一个User has_many Plans ,一个Plan属于一个User ),我想在语法中使用什么?为什么?
编辑1:另外,如果你解释了它是如何工作在form_helper或一个常规的forms,这将是非常棒的。 想象一下,你正在向理解Web开发的Web开发人员解释这一点,但对于Rails来说是相对较新的。 你会如何解释?
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. )
或者你的例子可以用下面的代码来表示:
<select name="post[author_id]"> <% Author.all.each do |author| %> <option value="<%= author.id %>"><%= author.name_with_initial %></option> <% end %> </select>
这不是在FormBuilder ,而是在FormOptionsHelper
我花了相当一段时间在自己的select标签的排列。
collection_select从一组对象中构build一个select标记。 牢记这一点,
object : object名称。 这用于生成标签的名称,并用于生成选定的值。 这可以是一个实际的对象或符号 – 在后一种情况下, 在ActionController的绑定中查找该名称的实例variables(即:post在您的控制器中查找名为@post的实例var)。
method : method名称。 这用于生成标签的名称。换句话说,您正试图从select中获取的对象的属性
collection :对象的集合
value_method :对于集合中的每个对象,此方法用于值
text_method :对于集合中的每个对象,此方法用于显示文本
可选参数:
options :您可以传递的选项。 这些logging在选项标题下。
html_options :无论传递到这里,只是添加到生成的html标签。 如果你想提供一个类,ID或任何其他属性,它会在这里。
你的联系可以写成:
collection_select(:user, :plan_ids, Plan.all, :id, :name, {:prompt => true, :multiple=>true })
关于使用form_for ,再次用非常简单的术语来说,对于form_for所有标签,例如。 f.text_field ,你不需要提供第一个( object )参数。 这取自form_for语法。