Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Handling in ActiveRecord Transactions?

I need to create a row in both tickets and users table... I just need to know how to process in case the transaction fails.

@ticket.transaction do     @ticket.save!     @user.save! end     #if (transaction succeeded)         #.....     #else (transaction failed)         #......     #end 

On a side note I'd just like to thank everyone who participates at stack overflow for helping a designer learn more programming... I appreciate the time you guys take out of your day to answer n00b questions like this :)

like image 244
Kevin Avatar asked Dec 21 '09 01:12

Kevin


People also ask

How does ActiveRecord transaction work?

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.

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

If you are using the save! method with a bang (exclamation point), the application will throw an exception when the save fails. You would then have to catch the exception to handle the failure.

begin   @ticket.transaction do     @ticket.save!     @user.save!   end   #handle success here rescue ActiveRecord::RecordInvalid => invalid    #handle failure here end 
like image 97
MattMcKnight Avatar answered Sep 27 '22 19:09

MattMcKnight