I have a query that begins and ends a transaction like this:
transaction = "BEGIN; UPDATE articles set x = 1 where id = 1; UPDATE articles set x = 2 where id = 2; END;"
ActiveRecord::Base.connection.execute(transaction)
My question: Do I even need the BEGIN and END? Does ActiveRecord already wrap my query into a transaction?
Transactions in ActiveRecordEvery database operation that happens inside that block will be sent to the database as a transaction. If any kind of unhandled error happens inside the block, the transaction will be aborted, and no changes will be made to the DB.
Returns a new relation, which is the result of filtering the current relation according to the conditions in the arguments.
Rails transactions are tied to one database connectionAnd as long as the transaction block is running this one database connection is open. So try to do as little as needed inside the transaction block, otherwise you will be blocking a database connection for more time than you should.
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
ActiveRecord provides the transaction method, available on both AR classes and instances, that will wrap queries within a given block. It even supports nested transactions.
You could rewrite your code as:
sql = <<-SQL
UPDATE articles set x = 1 where id = 1;
UPDATE articles set x = 2 where id = 2;
SQL
ActiveRecord::Base.transaction do
ActiveRecord::Base.connection.execute(sql)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With