Transaction with Exception Handling in Ruby On Rails
I was looking for transaction with exception handling in Ruby On Rails .. after testing some examples provided in various sites, I just modify my code & made my own logic to handle the exception. Its very easy & cool .. :)
def delTm
@tmId = 0
@exception = false
if(params[:tmId])
@tmId = params[:tmId]
end
# Transaction Block start ..........
Timesheet.transaction do
# transaction begin .........
begin
@tm = Timesheet.find(@tmId)
@tmStatus = getTmStatus(@tm.status_id)
if(@tmStatus != "Approved")
@allEffort = Effort.find(:all,:conditions=>"timesheet_id=#{@tmId}")
@allEffort.each do |e|
e.delete
end
@tm.delete
end
# use rescue to handle any exception in above block ...
# I avoid to check a particular kindda exception therefore i just use raise Exception.
# Whatever the exception will occur it will trap and then the next block of ocde will work
#rescue ActiveRecord::RecordInvalid
rescue Exception
# Write your own logic ....
@exception = true
# Now Rollback all the changes made in database ...
# use raise ActiveRecord::Rollback
raise ActiveRecord::Rollback
end
# End transaction block ....
end
end
def delTm
@tmId = 0
@exception = false
if(params[:tmId])
@tmId = params[:tmId]
end
# Transaction Block start ..........
Timesheet.transaction do
# transaction begin .........
begin
@tm = Timesheet.find(@tmId)
@tmStatus = getTmStatus(@tm.status_id)
if(@tmStatus != "Approved")
@allEffort = Effort.find(:all,:conditions=>"timesheet_id=#{@tmId}")
@allEffort.each do |e|
e.delete
end
@tm.delete
end
# use rescue to handle any exception in above block ...
# I avoid to check a particular kindda exception therefore i just use raise Exception.
# Whatever the exception will occur it will trap and then the next block of ocde will work
#rescue ActiveRecord::RecordInvalid
rescue Exception
# Write your own logic ....
@exception = true
# Now Rollback all the changes made in database ...
# use raise ActiveRecord::Rollback
raise ActiveRecord::Rollback
end
# End transaction block ....
end
end

Leave a Comment