ActiveRecord 事务不引发错误

ActiveRecord transactions not raising errors

我已经设置了一个 ActiveRecord 事务,但是当第二个语句失败时,它并没有导致事务失败。这是我的代码:

  Contact.transaction do
    contact = Contact.create(params)
    channel = ContactChannel.create(contact: contact, phone: contact.phone)
    # ContactChannel query raises a validation error
    # puts "ERRORS: #{channel.errors.messages}" outputs the following:
    #      {:channel_key=>["has already been taken"]}
    contact # Still returns the contact that was created
  end

知道为什么尽管有验证错误但不会失败吗?

create! 而不是 create 应该引发异常,这应该会导致事务回滚。基本上是比较严格的版本,如果没有抛出异常,交易不会失败。

要获取事务回滚的原因,您可以将事务语句包装在 begin (...) rescue - 块中并捕获 ActiveRecord::Rollback- 错误并将其消息用于 return交易失败的原因。