Alex Rivera | Logout

Rails transaction doesn't rollback on validation error

Asked 2010-02-11T16:48:22.643
11

I have two models: user and company. They both get created from one form and I'm using a transaction like this:

 User.transaction do

  @user.save!

  @company.user = @user
  @company.save!

  @user.reload
  @user.company = @company
  @user.save!

 flash[:notice] = "Thank you for your registration."
  redirect_to_index
end

The user gets saved to the database even when one of the company's validations fails. I've tried adding explicit error handling of ActiveRecord::RecordInvalid but it didn't help. I thought the validation would raise the error to rollback the transaction anyway. Any help is greatly appreciated.

Thanks

Edit
Report

1 Answer

-3

http://tempe.st/2007/05/transaction-in-rails/

I believe you must use a begin end block outside the transaction loop.

answered 2010-03-06T23:24:19.943

Your Answer