diff --git a/2016-09-09.md b/2016-09-09.md index 6768587..b2924bc 100644 --- a/2016-09-09.md +++ b/2016-09-09.md @@ -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 +~~~