2016年5月2日 星期一

Nested transactions



User.transaction do
  User.create(username: 'Kotori')
  User.transaction do
    User.create(username: 'Nemu')
    raise ActiveRecord::Rollback
  end
end
both Koori, Nemu created

As mentioned previously ActiveRecord::Rollback does not propagate outside of the containing transaction block and so the parent transaction does not receive the exception nested inside the child. Since the contents of the child transaction are lumped into the parent transaction both records are created! I find it easier to think of nested transactions like the child who dumps its contents into the parent container, leaving the child transaction empty.

User.transaction do
  User.create(username: 'Kotori')
  User.transaction(requires_new: truedo
    User.create(username: 'Nemu')
    raise ActiveRecord::Rollback
  end
end

only “Kotori” is created 

沒有留言:

張貼留言