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 :)
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.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With