首页 > 解决方案 > 如何在表单中为 HMABTM 关系 Rails 添加多条记录

问题描述

我有一个模型Landings和一个模型Products

有一个has_many_and_belongs_to_many关联,带有一个连接表landings_products

我希望能够products从创建和编辑landing表单中添加各种内容。

我添加了一个这样的选择,在其中我得到一个带有可选产品的下拉列表,但我只能为每个着陆选择一个产品,并且我希望能够添加尽可能多的产品:

<%= form_with(model: landing, local: true) do |form| %>
    <%= select_tag("landing[product_ids][]", options_from_collection_for_select(Product.all, :id, :name)) %>
    <%= form.submit "Crear landing page", class: "btn btn-primary"  %>
<% end %>

此外,我已将着陆控制器中的 product_ids 列入白名单。

¿如何为我的模型从同一个表单中添加多个产品?

非常感谢提前

标签: ruby-on-railsruby

解决方案


一种方法是使用#collection_check_boxes

<%= form_with(model: landing, local: true) do |form| %>
    <%= form.collection_check_boxes(:product_ids, Product.all, :id, :name) %>
    <%= form.submit "Crear landing page", class: "btn btn-primary"  %>
<% end %>

推荐阅读