stackjlei
stackjlei

Reputation: 10035

SQL statement vs. active record

In the rails guides about transactions it says that sql statements are put together like below:

ActiveRecord::Base.transaction do
  david.withdrawal(100)
  mary.deposit(100)
end

But isn't this active record? What is the difference?

Upvotes: 0

Views: 91

Answers (2)

George
George

Reputation: 680

You execute Ruby or Active Record methods or SQL inside a ActiveRecord::Base.transaction block the same way you do outside of one. The only difference is that if any of the database actions that happen in the block fail, all other database actions from the block are rolled back as well.

Active Record is a Ruby wrapper around SQL. To see how Active Record methods translate to SQL, look at the examples in the Active Record docs.

In the example you posted:

ActiveRecord::Base.transaction do
  david.withdrawal(100)
  mary.deposit(100)
end

:withdrawal and :deposit can be assumed to be Active Record methods that end up making SQL calls. The withdrawal relies on the deposit, so we wrap them in a transaction so if either fails, the other will be rolled back(cancelled) too.

Upvotes: 0

Nitin
Nitin

Reputation: 7366

You are asking about david.withdrawal(100) here I think. This is not active_record nor sql statement. It is just statement to help user to understand use of transactions in rails.

You can use active record inside transactions block. You can also write sql statement but in rails way only.

Transactions are used, If you have some dependent sql statements. If any one is failed to save in DB, then other statements should also rolled back. In such cases we used transactions.

Upvotes: 1

Related Questions