I have a Comment model which belongs_to a Topic model. On the Comment model, I have a before_create callback
def on_create
Topic.transaction(:require_new =
PostgreSQL requires SET TRANSACTION
statements to be executed after a transaction starts and before any DML (SELECT, INSERT, DELETE, etc.) statement. From the documentation, it looks like all that stuff will have to be done through the connection object, not the transaction object. Something like (untested)
Topic.connection.begin_db_transaction
Topic.connection.execute('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
# Other things go here. I'd test with another literal SQL statement to make
# sure it works like I'd hope it does. Then possibly try rewriting in Rails.
Topic.connection.commit_db_transaction
I really hope I'm wrong about that.
One distasteful alternative is to change the default isolation level for all transactions on the PostgreSQL server. (Search http://www.postgresql.org/docs/current/static/runtime-config-client.html for "default_transaction_isolation ".) But that feels like using a cannon to kill a fly.
You may find transaction_isolation gem helpful: https://github.com/qertoip/transaction_isolation
As of Rails 4, #transaction provides an :isolation option:
If your database supports setting the isolation level for a transaction, you can set it like so:
Post.transaction(isolation: :serializable) do # ... end