【问题标题】:How to create select tag in form_for Rails如何在 form_for Rails 中创建选择标签
【发布时间】:2017-09-07 12:46:27
【问题描述】:

我正在尝试在 form_for 中创建一个选择标签,我可以在其中从选项中选择多个类别。我看过Rails documentation 和这个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| %>

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

【问题讨论】:

  • 那么,您有选择多个项目的问题吗?
  • 不,选择标签工作正常。我可以选择多个类别,但提交表单时它不会保存到数据库中。
  • 字段名称是什么?还发布一些 ruby​​ 代码和参数。
  • 您可能应该使用选择助手来生成选择标签,因为很可能缺少持久化数据所需的属性。 &lt;%= select_tag :department_id, class: 'selectpicker', multiple: true, ...etc %&gt;

标签: html ruby-on-rails erb form-for


【解决方案1】:

它不起作用,因为您的选择未限定到您的 @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

【讨论】:

  • 所以我输入了&lt;%= f.collection_select(:category_ids, Category.all, :id, :name, class: "selectpicker", data-style: "form-control", multiple: true, title: "Choose Department(s)", data-size: "5") %&gt; ,它抛出了一个错误。我认为这是因为数据样式和数据大小中的连字符。知道如何将其识别为要更改的选择标签的属性吗?
  • 更新了我的答案。您可以使用 data: { size: 5, style: 'form-control' } 之类的内容传递自定义 HTML 属性(例如 HTML5 data-)。
  • 我最终使用了&lt;%= f.collection_select(:category_ids, Category.all, :id, :name,{:"data-style" =&gt; "form-control", multiple: true, :"data-size" =&gt; "5"}, {class: "selectpicker", title: "Choose Department(s)"}) %&gt; 。现在唯一的问题是“multiple”不起作用。
  • 如何在控制器中保存category_ids 的数组?假设您使用Strong Parameters,您必须首先将category_ids 替换为category_id,并将允许的参数声明为category_id: []
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多