如何在 form_for Rails 中创建 select 标签

How to create select tag in form_for Rails

我正在尝试在 form_for 中创建一个 select 标签,我可以从选项中 select 多个类别。我查看了 Rails documentation and this SO,但它们似乎都不起作用。到目前为止,我有这个:

<select class="selectpicker" data-style="form-control" multiple title="Choose Department(s)" data-size="5">
   <%= options_from_collection_for_select(Category.all, :id, :name)%>
</select>

我的 form_for 看起来像这样:

<%= form_for(@listing, :html => {class: "form-horizontal" , role: "form"}) do |f| %>

我的列表可以有很多类别。我应该如何将其保存到我的表格中?现在,当我提交表单时,类别没有保存。

它不起作用,因为您的 select 不在您的 @listing 对象范围内。尝试:

<%= f.collection_select(:category_id, Category.all, :id, :name) %>

解决@ddubs 的评论,建议用 Rails 表单助手替换 select 标签并保留您的自定义 HTML 数据属性:

<%= f.collection_select(:category_ids, Category.all, :id, :name, {}, class: "selectpicker", title: "Choose Department(s)", multiple: true, data: { style: "form-control", size: "5" }) %>

有关 collection_select 选项的更多信息,请查看 Rails api

正如 mmichael 指出的那样,最终答案是 <%= f.collection_select(:category_ids, Category.all, :id, :name,{:"data-style" => "form-control", :"data-size" => "5"}, {class: "selectpicker", title: "Choose Department(s)", multiple: true}) %>