在我的Contract
表单中,我允许用户从下拉框中选择Unit
,或者从一组复选框中选择多个单位。下拉字段名为unit_id
,多个复选框名为multi_unit_ids[]
。 (由于这两个选项都在页面上,我不能使用相同的名称。)
每个单位选择创建一份合约。因此,如果只选择了1个单位,则只会使用Contract
创建一个unit_id
。但是,在选择多个单位时,所创建的每个Contract
的所有数据都相同,但每个数据都有自己的单位ID(从multi_unit_ids数组中提取)。
以下是我create
的{{1}}方法中的代码:
contracts_controller.rb
这一切看起来都很混乱!有什么更好的方法呢?
答案 0 :(得分:1)
嗯,就没有循环创建这些数据库条目而言,我无法提出太多建议。我不确定这是否可能,并且真的那个循环看起来并不那么混乱,除非你遗漏了# ... other code here
部分的混乱。
事实上,我要提出的建议可能会让你觉得代码更混乱。
如果您打算创建大量数据库行,那么将循环包装在ActiveRecord::Base.transaction
中类似于:
# Loop through units
ActiveRecord::Base.transaction do
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
end
或者,否则使用其他方法将创建组合到单个查询中(http://www.coffeepowered.net/2009/01/23/mass-inserting-data-in-rails-without-killing-your-performance/还有其他选项和基准)。
就重构而言,我不能在这里提供太多。