Rails - 在 simple_form 中使用 collection_select 用于 has_many_through 关联

Rails - use collection_select in a simple_form for a has_many_through association

我需要有关为 has_many_through 关联创建表单的帮助,该关联还指定了 class 名称:

class Sponsor < ActiveRecord::Base
  has_many :member_contacts
  has_many :contacts, through: member_contacts, class_name: :member

  accepts_nested_attributes_for :address, :contacts
end

class Contact < ActiveRecord::Base
  has_many :member_contacts
  has_many :sponsors, through: member_contacts
end

class MemberContact  < ActiveRecord::Base
  belongs_to :contact
  belongs_to :sponsor
end

sponsors_controller.rb

def create
  @sponsor = Sponsor.create(sponsor_params)
  @sponsor.contacts.build
end

def sponsor_params
  params.require(:sponsor).permit(:name,:website,:email, 
  :contact_first_name, :contact_surname, contacts_attributes: [], address_attributes: [:flat, :street, :postal_code, :city])
end

sponsor/_form.html.haml

= simple_form_for @sponsor do |f|
  = f.association :contacts, collection: Member.all, label_method: :full_name

失败并出现错误 'unpermitted params, contact_ids',因为

"contact_ids"=>["", "4", "5", "6"]

正在参数哈希中传递。在表格中,我想要一个包含所有成员的下拉列表以及 select 多个成员的能力,这些成员将作为联系人保存在发起人面前。

如何在控制器中设置 contacts_attributes in sponsor_params 和视图中的 collection_select simple_form helper?

为了使表单正常工作,我向赞助商添加了一个外键 class

has_many :contacts, through: member_contacts, class_name: 'Member', foreign_key 'member_id'

更改了控制器中的强参数

def sponsor_params
  params.require(:sponsor).permit(:name,:website,:email, contact_first_name, :contact_surname, contact_ids: [], address_attributes: [:flat, :street, :postal_code, :city])
end

并删除视图中的关联,使用 collection_select

= f.collection_select :contact_ids, Member.all, :id, :full_name, 
      { selected: @sponsor.contacts.map(&:id) }, { multiple: true }

你可以这样设置:

params.require(:sponsor).permit(:name,:website,:email, contact_ids: []...)

请注意,permit(:contact_ids) 将失败,但 permit(contact_ids: []) 有效。