Rails 4 ActiveRecord事务块 - 回滚标准

时间:2016-01-13 21:37:46

标签: ruby-on-rails activerecord transactions postgresql-9.1

您好我正在使用ActiveRecords Transaction块来制作一堆记录要么全部接受,要么全无。 我在模型中包含了事务块,并从控制器调用整个函数:

  def self.write_atomic_union_sync
   Union.transaction do
     @sync=Sync.create(sync_date: DateTime.now, user_id: user_id)
     union_array.map do |t|
        Union.create(value2: t[:value2], user_id:t[:user_id],value1: t[:value1],sync_id: @sync[:id])
        #sync.unions.create(t)
     end
   end
  end

我对Union有一些限制,以避免重复的条目。 当我第一次发送测试数据时,带有联合记录的同步对象将存储到数据库中。但是,当我再次提交相同的数据时, 工会没有得到保存,但同步被写入。

Ruby API guide开始,在事务块中使用create方法是有效的,但我也试过在数组之前调用@sync.newunions.new,然后只放入{{事务块内的1}}等也没有太大的成功。

我认为这可能是因为union-create过程没有明确的ROLLBACK异常。但我无法弄清楚为什么.. 也许有人有一个有用的线索? 提前全部感谢!

@sync.save!

1 个答案:

答案 0 :(得分:0)

只有在引发异常时才会回滚事务块。您希望使用导致失败时出现异常的create版本:create!。这样,如果其中一个创建失败,它将引发一个异常,触发回滚。请注意,异常将传播到事务块之外,因此您必须在外部捕获它。尝试:

  def self.write_atomic_union_sync
    begin
      Union.transaction do
        @sync=Sync.create!(sync_date: DateTime.now, user_id: user_id)
        union_array.map do |t|
           Union.create!(value2: t[:value2], user_id:t[:user_id],value1: t[:value1],sync_id: @sync[:id])
           #sync.unions.create!(t)
        end
      end
    rescue
      # Handle the exception
    end
  end