在Rails中回滚?

时间:2015-07-17 18:53:20

标签: ruby-on-rails

在我的Rails应用程序中,我有一个复制许多行的方法,并继续复制一些父子关系。

def merge
   params[:merge_rows].each do |merge_row|
      batch_detail = BatchDetail.find(merge_row)
      batch_detail.duplicate
      batch_detail.batch_id = batch.id
      batch_detail.save
   end
   render nothing: true
end

# BatchDetail.duplicate
def duplicate
  batch_detail = dup
  batch_detail.primer3_parameter = primer3_parameter.dup if primer3_parameter.present?
  primer3_outputs.each do |primer3_output|
    batch_detail.primer3_outputs << primer3_output.duplicate
  end
  batch_detail
end

理想情况下,我想只保存所有行成功复制,并且如果有任何不成功则回滚所有更改。

然后,如果成功或错误,我想通过渲染报告200或500.

1 个答案:

答案 0 :(得分:1)

在事务块中包装ActiveRecord更改,如果某个例外绕过了块的function addInt($counter2) { $Int = array("select" => "Interface_Type_".$counter2, "dropdown" =>"Int_Client_Port_".$counter2, "dropdown2" => "Int_Server_Port_".$counter2, "dropdown3" => "Int_Uplink_".$counter2, "textbox" => "Int_Desc_" .$counter2, "select2" => "Int_Type_" .$counter2, "dropdown4" => "Switchport_" .$counter2, "dropdown5" => "Routed_Port_" .$counter2, "textbox2" => "Switchport_VLAN" .$counter2, "textbox3" => "IP_Routed_Port"); $Values = array("radio" => "Routable", "radio2" => "Not Routable", "dropdown" => "Client Port", "dropdown2" => "Server Port", "dropdown3" => "Uplink", "dropdown4" => "Switchport", "dropdown5" => "Routed Port"); $addInterface = new Templates($Int, $Values); $addInt = "<div name='Add_Interface_Type_" .$counter2. "' style=''> Interface type: "; $addInt .= $addInterface->select. "<option>--Please Select--</option>"; $addInt .= $addInterface->dropdown. " Client Port </option>"; $addInt .= $addInterface->dropdown2. " Server Port </option>"; $addInt .= $addInterface->dropdown3. " Uplink </option> </select>"; $addInt .= "<br> Description:" .$addInterface->textbox. "<br>"; $addInt .= $addInterface->select2. "<option>--Please Select--</option>"; $addInt .= $addInterface->dropdown4. "Switchport </option>"; $addInt .= $addInterface->dropdown5. "Routed Port </option> </select>"; $addInt .= "<div name='Switchport_Div_" .$counter2. "' style='display:none'> VLAN: " .$addInterface->textbox2; $addInt .= "</div> <br><div name='Routed_Port_Div_".$counter2."' style='display:none'> IP Address:"; $addInt .= $addInterface->textbox3. "</div> </div>"; return $addInt; } if ($_POST['calladdInt'] == "1") { echo addInt($_POST['counter2']); }' ,则回滚所有更改。

end