回滚事务不使用块 [英] Rolling back Transactions Without using a Block
问题描述
注意:这是一个后续问题的优化Rspec的测试,以避免重复复杂的设置Proceedures 的
Note: This is a follow up question to Optimising Rspec Tests to Avoid Repeating Complex Setup Proceedures
有关原因是这个问题的范围(见上述注),我希望能够启动Rails的数据库事务,然后回滚该交易在不同的范围。例如:
For reasons that are outside the scope of this question (see the note above), I want to be able to start a Rails database transaction and then rollback that transaction in a different scope. E.g:
def before_callback
start_transaction # Start the transaction
# Create/Update some records
end
def after_callback
rollback_transaction # Rollback changes from before_callback and do_stuff
end
def do_stuff
before_callback
# Do some stuff
after_callback
end
do_stuff
我意识到这是交易中的人为例子可以很容易地来解决办..结束
和一个小重构,但在上下文心目中 do_stuff
的是,我真的不希望惹外部插件的一部分。有没有办法做到像我在Rails的刚才所描述的东西吗?
I realize this is a contrived example which could be resolved easily with transaction do .. end
and a little refactoring, but in the context have in mind do_stuff
is part of an external plugin that I really don't want to mess with. Is there a way to do something similar to what I just described in Rails?
推荐答案
有关原油快速和肮脏的解决方案,你可以只执行所需的SQL命令直接数据库连接的:
For a crude quick-and-dirty solution you could just execute the required SQL commands directly on the database connection:
def start_transaction
ActiveRecord::Base.connection.execute("BEGIN")
end
def rollback_transaction
ActiveRecord::Base.connection.execute("ROLLBACK")
end
另外在看事务的源
方法可能给你如何以更精致的方式处理这一一些想法。
Also looking at the source of the transaction
method might give you some ideas on how to approach this in a more refined manner.
(你可以找到它在的ActiveRecord :: ConnectionAdapters ::在
) DatabaseStatements
的lib / active_record / connection_adapters /抽象/ database_statements.rb
(You can find it in ActiveRecord::ConnectionAdapters::DatabaseStatements
in lib/active_record/connection_adapters/abstract/database_statements.rb
)
这篇关于回滚事务不使用块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!