我正在创建一个提交"提交的应用程序"可以使用创建客户详细信息的表单进行,并允许"推荐"根据可提供所需服务的分支来创建
class Submission < ActiveRecord::Base
has_many :referrals, :inverse_of => :submission, dependent: :delete_all
accepts_nested_attributes_for :referrals, :allow_destroy => true
end
class Referral < ActiveRecord::Base
belongs_to :submission
end
class Branch < ActiveRecord::Base
has_many :referrals
end
提交控制器:
def new
@submission = Submission.new
@submission.build_client
@submission.client.build_address
@submission.referrals.build
end
def submission_params
params.require(:submission).permit(:consent, :user_id, client_attributes:
[:client_id, :first_name,
address_attributes:
[:first_line, :second_line,]
],
referrals_attributes:
[:branch_id]
)
end
提交表格:
<%= form_for(@submission) do |f| %>
<%= f.fields_for :referrals do |referral| %>
<%= render 'referral_fields', f: referral %>
<% end %>
<% end %>
_referral_fields.html.erb:
<% Branch.all.where(referrable: true).each do |branch| %>
<label>
<%= check_box_tag 'branch_ids[]', branch.id %>
<%= branch.name %>
</label>
<% end %>
我想要的是为每个可引用分支设置复选框。勾选分支并创建提交时,将为该分支创建引用。但是,当我提交表单时,我得到的验证错误是&#34;引荐不能为空白&#34;。知道为什么这不起作用吗?
非常感谢任何帮助
答案 0 :(得分:3)
<% # _referral_fields.html.erb %>
<%= f.collection_check_boxes(:branch_ids, Branch.where(referrable: true), :id, :name) do |b|
b.label { b.check_box } # wraps check box in label
end %>
您需要将submission[referrals_attributes][branch_ids]
列入白名单 - 而不是branch_id
。
def submission_params
params.require(:submission)
.permit(
:consent,
:user_id,
client_attributes: [
:client_id,
:first_name,
address_attributes: [
:first_line, :second_line,
]
],
referrals_attributes: [:branch_ids]
)
end
然而,要使其工作,您需要在Referral和Branch之间设置关系。在这种情况下,您可以使用has_and_belongs_to_many
(HABTM)或has_many though:
(HMT)关系。
请参阅Choosing Between has_many :through and has_and_belongs_to_many。
class Referral < ActiveRecord::Base
belongs_to :submission
has_and_belongs_to_many :branches
end
class Branch < ActiveRecord::Base
has_and_belongs_to_many :referrals
end
您还需要创建一个连接表:
rails g migration CreateBranchReferralJoinTable branch referral