在同一事务中同时执行删除和插入记录操作吗?

时间:2017-05-15 00:42:33

标签: ruby-on-rails postgresql activerecord

我发现在rails destroy方法中,一个额外的事务将包装在查询上。因此,当我尝试以下时,它不起作用。

ActiveRecord::Base.transaction do 
 @model_a.destroy_all
 @new_model_list.each do |item|
  item.create!
  # Error occurs some point
  # No rollback for those deleted records
 end
end

1 个答案:

答案 0 :(得分:0)

尝试将其重写为:

ActiveRecord::Base.connection.transaction do 
 @model_a.destroy_all
 @new_model_list.each do |item|
  item.create!
  # Error occurs some point
  # No rollback for those deleted records
 end
end