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

时间:2015-07-26 12:17:31

标签: ruby-on-rails-4 simple-form nested-attributes has-many-through

我需要有关has_many_through关联的创建表单的帮助,该关联还指定了一个类名:

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

赞助/ _form.html.haml

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

这是因为错误'未经许可的params,contact_ids'而失败,因为

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

正在params散列中传递。在表单中,我想要一个所有成员的下拉列表,以及选择多个成员的能力,这些成员将作为联系人保存在赞助商之间。

如何在控制器的sponsor_params中设置contacts_attributes,在视图中设置collection_select simple_form帮助器?

2 个答案:

答案 0 :(得分:0)

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

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 }

答案 1 :(得分:0)

您可以这样设置:

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

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