collection_select中的选项在提交时创建了一个新选项-Rails 5 [英] Option from collection_select creates a new one on submit - Rails 5

查看:134
本文介绍了collection_select中的选项在提交时创建了一个新选项-Rails 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我一直在研究插件和类别之间的HABTM关联.我几乎可以正常工作了,但是在collection_select上遇到了麻烦.

Today I've been working on a HABTM association between my Plugins and Categories. I got it almost working, but run into trouble with the collection_select.

我在表单中有一个选择,并且成功调用了所有现有的类别,但是当我提交表单时,将创建一个新的类别.例如,我选择类别Synthesizer.提交时,突然有两个类别称为合成器".如何使插件与类别相关联,但不创建新的插件?

I have a select in my form and I succesfully call all the existing Categories, but when I submit the form, a new Category is created. For example I select the category Synthesizer. When I submit, I suddenly have two categories called Synthesizer. How can I make it so that the Plugin is associated with the Category, but does not create a new one?

这是我表单中的代码:

<%= f.fields_for :categories do |c| %>
  <%= c.label :name %>
  <%= c.collection_select :name, Category.order(:name), :name, :name, multiple: true, include_blank: true %>
<% end %>

这是我设置强参数的方式:

This is how I've set my strong params:

def plugin_params
  params.require(:plugin).permit(:name, :url, :image, :description, :categories_attributes => [:id, :name])
end

在我的插件模型中:

has_and_belongs_to_many :categories
accepts_nested_attributes_for :categories

如果您错过背景信息,请告诉我.在此先感谢您的帮助! :)

If you miss context, please let me know. Thanks a lot in advance for your help! :)

推荐答案

一个真正常见的新手误解是,您需要使用嵌套属性来分配关联. 嵌套属性用于以与插件相同的形式创建全新的类别(或编辑现有的类别),通常最好避免这种情况.

A really common newbie misconception is that you need nested attributes to assign associations. Nested attributes is used to create brand new categories (or edit existing ones) from the same form as the plugin and is usually best avoided.

请记住,categories_plugins联接表上的类别和行之间存在巨大差异.您要稍后创建.

Remember here that there is huge difference between categories and rows on the categories_plugins join table. You want to create the the later.

您真正需要做的就是使用_idssetter/getter: :Associations :: ClassMethods-label-Collection + associations + -28one-to-many + -2F + many-to-many-29"rel =" nofollow noreferrer> has_and_belongs_to_many .

All you really need to to do is use the _ids setter / getter created by has_and_belongs_to_many.

class Plugin
  has_and_belongs_to_many :categories
end

<%= form_with(model: @plugin) do |f| %>
  # ...
  <%= c.collection_select :category_ids, Category.order(:name), :id, :name, multiple: true, include_blank: true %>
  # ...
<% end %>

def plugin_params
  params.require(:plugin).permit(:name, :url, :image, :description, category_ids: [])
end

category_ids=设置器将自动处理将行插入/删除到category_plugins连接表中.

The category_ids= setter will handle inserting/deleting rows into the categories_plugins join table automatically.

这篇关于collection_select中的选项在提交时创建了一个新选项-Rails 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆