我正在浏览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有许多PlansPlan属于User)解释一下我想在语法中使用什么,为什么?

Edit 1:此外,如果你解释一下它在form_helper或常规表单中是如何工作的,那就太棒了.想象一下,您正在向一位了解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中有记录

Ruby-on-rails相关问答推荐

使用Rails和RSpec,有没有办法查看操作真正将您带到哪个页面?

Ruby/Rails 相当于 Python 的 sys.addAuditHook

GroupingError:错误:列必须出现在 GROUP BY 子句中或在聚合函数中使用

Rails 5:如何从数据库中删除列?

有没有办法在 Rails 3.1 中检测用户代理

跳过模型中的某些验证方法

在 Nokogiri 中获取属性值以提取链接 URL

如何在rails中发回js.haml

Rails ActiveRecord 查询日期范围

Rails - 使用 %W

没有图像时如何在回形针中显示隐藏图像

带有查询字符串参数的 Rails 动作缓存

在 rake 任务期间关闭观察者的简单方法?

如何解决弃用警告方法 to_hash 已弃用并将在 Rails 5.1 中删除

使用god 监控独角兽 - 以非零代码开始退出 = 1

嵌套模型和父验证

活动管理员:仅自定义新表单

如何在每个操作的基础上禁用 Ruby on Rails 的日志(log)记录?

我是否必须手动卸载所有依赖的 gem?

停止 Rails 为视图和助手生成规范测试?