Skip to content

Commit

Permalink
Adds transactions example
Browse files Browse the repository at this point in the history
  • Loading branch information
HarshwardhanSingh committed Sep 9, 2016
1 parent cd4296a commit 14db4d3
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions 2016-09-09.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,22 @@ Harshwardhan Singh Rathore

5. (Rails) Always use ActiveRecord transactions to bind database calls while running multiple database operation.
This will rollback all the changes to database if any one of the database query fails.
~~~ruby
ModelClass.transaction do
User.create!(email: params[:email], username: params[:username])
Profile.create!(email: params[:email], name: params[:name])
end
~~~
In above mentioned case if `User` create query succeeds but `Profile` create fails then the user created by `User.create!(email: params[:email], username: params[:username])`
will be deleted. That's the beauty of using transactions that it rollbacks to the previous state if anything goes wrong.

If you don't use transactions but want to achieve the same functionality then the code will look like this

~~~ruby
user = User.create!(email: params[:email], username: params[:username])
profile = Profile.create!(email: params[:email], name: params[:name])

unless profile do
user.destroy
end
~~~

0 comments on commit 14db4d3

Please sign in to comment.