Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when you do activeRecord.save does the transaction commit or is when the method exits?

In Rails 3, when you do activeRecord.save does the transaction commit or is when the method exits ?

so what I'm trying to figure out is if the MySQL is written right after save! or it's save after I exit the define black

def something
  1000.times do
       o = Order.new(:name => "Tomas")
       o.save
  end
end 
like image 678
equivalent8 Avatar asked Jun 06 '11 15:06

equivalent8


People also ask

What is an ActiveRecord transaction?

Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. Transactions are used to enforce the integrity of the database and guard the data against program errors or database break-downs.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...

What are ActiveRecord methods?

The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save.

What is ActiveRecord base transaction in rails?

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.


1 Answers

You should probably read up a bit on the ActiveRecord object callback chain; it explains what is going on under the hood with your objects.

Basically, when you call save, an ActiveRecord::Base object will go through all the callbacks in the order the documentation lists them, you can see where the commit takes place (in between steps 6 and 7 as of my writing this). ActiveRecord even exposes a callback after the commit happens in case you want some conditional logic when you're sure something has been committed to the database, but generally we trust that if save returns true, everything is fine.

So to explicitly answer your question, a commit happens during your save call, not when you exit the method.

like image 88
Brett Bender Avatar answered Sep 22 '22 13:09

Brett Bender