有人可以用清晰、简单的术语向我解释 collection_select 吗? [英] Can someone explain collection_select to me in clear, simple terms?
问题描述
我正在浏览 collection_select
的 Rails API 文档,它们太糟糕了.
I am going through the Rails API docs for collection_select
and they are god-awful.
标题是这样的:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
这是他们提供的唯一示例代码:
And this is the only sample code they give:
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, :prompt => true)
有人可以解释一下,使用一个简单的关联(比如一个 User
has_many Plans
,一个 Plan
属于一个 User
),我想在语法中使用什么以及为什么?
Can someone explain, using a simple association (say a User
has_many Plans
, and a Plan
belongs to a User
), what I want to use in the syntax and why?
编辑 1:此外,如果您能在 form_helper
或常规表单中解释它是如何工作的,那就太好了.想象一下,您正在向一位了解 Web 开发但对 Rails 相对较新"的 Web 开发人员解释这一点.你会怎么解释?
Edit 1: Also, it would be awesome if you explained how it works inside a form_helper
or a regular form. Imagine you are explaining this to a web developer that understands web development, but is 'relatively new' to Rails. How would you explain it?
推荐答案
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.
)
或者您的示例可以表示为以下代码:
Or your example can be represented as the following code:
<select name="post[author_id]">
<% Author.all.each do |author| %>
<option value="<%= author.id %>"><%= author.name_with_initial %></option>
<% end %>
</select>
这不在 FormBuilder
中记录,而是在 FormOptionsHelper
This isn't documented in the FormBuilder
, but in the FormOptionsHelper
这篇关于有人可以用清晰、简单的术语向我解释 collection_select 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!