Wrap all controller actions in transactions in Rails
For info, I did this with an around_filter in my application controller:
around_filter :wrap_in_transactiondef wrap_in_transaction ActiveRecord::Base.transaction do yield endend
This just rolls back the transaction on any unhandled exception, and re-raises the exception.
Can it be done? probably.Should it be done? probably not, otherwise this would be part of rails, or there would already be a great gem for this.
If you have particular complex controller actions that are doing lots of db activity, and you want them to be in a transaction, my advice is to get this business logic and persistence into a model method, and put your transaction there. This also gives you more control for the cases where you may not always want this to happen.
If you really, really want to do this anyway, I would bet you could do it with Rack middleware, like this (untested) one https://gist.github.com/1477287:
# make this class in lib/transactional_requests.rb, and load it on startrequire 'activerecord'class TransactionalRequests def initialize(app) @app = app end def call(env) ActiveRecord::Base.transaction do @app.call(env) end endend# and in the app configconfig.middleware.use "TransactionalRequest"