ruby-on-rails - 如何在表单中为 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 列入白名单。
¿如何为我的模型从同一个表单中添加多个产品?
非常感谢提前
解决方案
一种方法是使用#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 %>
推荐阅读
- python - fit_transform() 得到了一个意外的关键字参数“dtype”
- c# - 在 IronRuby 中使用 C# DLL
- javascript - 如何解释仍然丢失的 {{data}}?
- c# - 列表中的排序算法
- git - 是否有任何功能可以在新仓库中自动添加一些文件
- save - 如何设置 hg Mercurial 以在文件保存时自动提交?
- java - Android filterResults() 显示重复项
- google-maps - 我们可以在 Flutter 的谷歌地图上显示一些动态文本和标记吗?
- python - 如何从 mediawiki 中提取纯文本?
- chef-infra - NoMethodError ------------- nil:NilClass 的未定义方法 `[]'