1

在我的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 Contractcreated, 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

这一切似乎太混乱了!有什么更好的方法来做到这一点?

4

1 回答 1

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 -没有杀死你的表现/)。

不过,就重构而言,我在这里不能提供太多。

于 2012-08-09T23:56:04.230 回答