如何在form_for Rails

时间:2017-09-07 12:46:27

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

我正在尝试在form_for中创建一个select标签,我可以从选项中选择多个类别。我查看了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| %>

我的商家信息可以包含多个类别。我怎么能把这个保存到我的表格中?现在,当我提交表单时,类别不会保存。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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}) %>