hi, i wanted to implement multidatabase transactions, in a project of mine.
The AWDR book by DHH and Sam Ruby, says that rails does not support easily the usecase where we are updating multiple databases concurrently.
eg: ==== CODE START ==== the Account and User models have different connections.
acc1 = Account.find(10) acc1 = Account.find(20)
begin Account.transaction do acc1.withdraw(100) acc2.deposit(100)
User.transaction do acc1.user.balance = acc1.balance acc1.user.save! acc2.user.balance = acc2.balance acc2.user.save! end raise "the Account model will be rolledback not not the User model as both the classes have diff. connections" end rescue Exception => err puts "Error | #{err.class} #{err.to_s} #{err.backtrace}" #to get the current values in the db [acc1.acc2].each {|x| x.reload } end
what will happen is that the changes for: acc1.withdraw(100) acc2.deposit(100)
will be rolled-back
but the changes for: acc1.user.balance = acc1.balance acc2.user.balance = acc2.balance
will not be rolledback, as they are on different database connections.
==== CODE END ====
How to solve this, how to keep the transaction across db connections. any ideas?
questions? 1) can i manually maintain the transaction, rather than a DSL. the DSL enforces a nesting relationship but i want a grouping relationship. 2) This same problem does not occur if the db connection is the same, how? 3) how do we check that two db connections are different, is <Model>.connection == <Model>.connection sufficient? 4) what does the option key :joinable do in active_record/ connection_adapters/abstract/database_statements.rb. it is not mentioned in the docs.
i wanted to implement multidatabase transactions. How do we do this? Has anyone faced this problem?
thanks for the help, deepak.