How to Conditionally Rollback a Transaction Using the PG Ruby Gem

Transactions rollback automatically if an exception is raised inside the block. So you just need to create a little Exception class for yourself, raise one inside the block, and then arrange to rescue it so your program doesn't error-exit due to the raised exception.

Try something like this:

class MyLittleIdError < StandardError
end

begin
  @conn.transaction do |conn|
    ins = conn.exec_prepared('insert', [i, "#{@words1[i % 100]} street"])
    raise MyLittleIdError if (ins[0]['id'].to_i % 2) == 0
  end
rescue MyLittleIdError
  puts "aha! we have rolled back."
end