Nick ONeill
Nick ONeill

Reputation: 7381

ActiveRecord transactions not raising errors

I've set up an ActiveRecord transaction, however when the second statement fails, it's not causing the transaction to fail. Here's my code:

  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

Any idea why this doesn't fail despite the validation error?

Upvotes: 1

Views: 942

Answers (1)

jfornoff
jfornoff

Reputation: 1378

create! instead of create should raise an exception, which should cause the transaction to be rolled back. It is basically a more strict version, and if no exception is raised, the transaction does not fail.

To get the reason for the transaction rollback, you can wrap your Transaction-statement in an begin (...) rescue - block and catch the ActiveRecord::Rollback- error and use its message to return the reason for the transaction failure.

Upvotes: 2

Related Questions