在我的Contract
表单中,我允许用户Unit
从下拉框中选择一个,或者从一组复选框中选择多个单位。下拉字段被命名unit_id
,多个复选框被命名multi_unit_ids[]
。(因为这两个选项都在页面上,所以我不能使用相同的名称)。
每个所选单位创建 1 个合同。因此,如果只选择了 1 个单位,则仅Contract
使用该unit_id
. However, when choosing multiple Units, all of the data is the same for each Contract
created, however each has their own Unit ID (pulled from the multi_unit_ids array).
这是我的create
方法中的代码 my contracts_controller.rb
:
# Multiple Units? Multiple Contracts
if params[:multi_unit_id]
unit_arr = params[:multi_unit_id]
else
unit_arr = [*params[:contract][:unit_id]]
end
# Loop through units
unit_arr.each do |unit_id|
# Assign the unit id to the params for easy creation
params[:contract][:unit_id] = unit_id
@contract = Contract.new(params[:contract])
# ... other code here
@contract.save
end
这一切似乎太混乱了!有什么更好的方法来做到这一点?