Rails transaction doesn't rollback on validation error Rails transaction doesn't rollback on validation error ruby-on-rails ruby-on-rails

Rails transaction doesn't rollback on validation error


You must use a database engine that supports ACID transactions. For mysql that is INNODB.

show table status\G

If users or companies is not using InnoDB engine, you can change it w/ this command.

ALTER TABLE <table name> ENGINE INNODB;

the exception thrown from @company.save! *should trigger a ROLLBACK command to be sent to the database. you can verify this in the console/logfile when running script/server with DEBUG log level.


attempting to save a new entry and revise an existing entry (based on the new entry) at the same time, ran into a similar problem. Tried transaction with rescue failed validation, but settled on this instead:

if @new_entry.valid? && @existing_entry.valid?  ActiveRecord::Base.transaction do    @new_entry.save!    @existing_entry.save!  endend

the code validates first. it doesn't attempt to save unless both entries are valid. transaction semantics guard against incomplete entry on other errors if the database supports it. hope that's a good solution.


You will have to consider these scenarios

  1. Use a database system that supports transaction
  2. Re-Factor that code for a more logical approach

As an example, if you only have a one-to-one relation, it can be handled in more optimized way

Company has_one UserUser belongs_to Company

Now, in Company model

@company.user.build(user_attributes)@company.save  # will save company as well as user

I have not tested it as an example. Just off my mind.Have I understood the problem correctly?