Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ActiveRecord wrap manual queries into a transaction already?

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?

like image 295
Henley Avatar asked Apr 23 '13 01:04

Henley


People also ask

How does ActiveRecord transaction work?

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.

What does ActiveRecord where return?

Returns a new relation, which is the result of filtering the current relation according to the conditions in the arguments.

How do rails transactions work?

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 in Ruby on Rails?

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.


1 Answers

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
like image 112
rossta Avatar answered Sep 20 '22 01:09

rossta