Getting started with Ruby on RailsRoutingActiveRecordViewsActiveRecord MigrationsRails Best PracticesNaming ConventionsActionCableActiveModelUser Authentication in RailsActiveRecord AssociationsActiveRecord ValidationsActiveRecord Query InterfaceActionMailerRails generate commandsConfigurationI18n - InternationalizationUsing GoogleMaps with RailsFile UploadsCachingActionControllerConfigurationSafe ConstantizeRails 5Authorization with CanCanMongoidGemsChange default timezoneAsset PipelineUpgrading RailsActiveRecord LockingDebuggingConfigure Angular with RailsRails loggerPrawn PDFRails APIDeploying a Rails app on HerokuActiveSupportForm HelpersActiveRecord TransactionsRSpec and Ruby on RailsDecorator patternElasticsearchReact with Rails using react-rails gemRails Cookbook - Advanced rails recipes/learnings and coding techniquesMultipurpose ActiveRecord columnsClass OrganizationShallow RoutingModel states: AASMRails 5 API AutheticationTesting Rails ApplicationsActive JobsRails frameworks over the yearsAdd Admin PanelNested form in Ruby on RailsFactory GirlImport whole CSV files from specific folderTools for Ruby on Rails code optimization and cleanupActiveJobActive Model SerializersRails Engine - Modular RailsSingle Table InheritanceActiveRecord TransactionsTurbolinksFriendly IDSecurely storing authentication keysAuthenticate Api using DeviseIntegrating React.js with Rails Using HyperloopChange a default Rails application enviornmentReserved WordsRails -EnginesAdding an Amazon RDS to your rails applicationPayment feature in railsRails on docker

ActiveRecord Transactions

Other topics

Getting Started with Active Record Transactions

Active Record Transactions can be applied to Model classes as well as Model instances, the objects within the transaction block need not all be instances of same class. This is because transactions are per-database connection, not per-model. For example:

User.transaction do
  account.save!
  profile.save!
  print "All saves success, returning 1"
  return 1
end
rescue_from ActiveRecord::RecordInvalid do |exception|
  print "Exception thrown, transaction rolledback"
  render_error "failure", exception.record.errors.full_messages.to_sentence
end

Using save with a bang ensures that transaction will be automatically rolled back when the exception is thrown and after the rollback, control goes to the rescue block for the exception. Make sure you rescue the exceptions thrown from the save! in Transaction Block.

If you don't want to use save!, you can manually raise raise ActiveRecord::Rollback when the save fails. You need not handle this exception. It will then rollback the transaction and take the control to the next statement after transaction block.

   User.transaction do
      if account.save && profile.save
        print "All saves success, returning 1"
        return 1
      else
        raise ActiveRecord::Rollback
      end
    end
    print "Transaction Rolled Back"

Contributors

Topic Id: 9326

Example Ids: 28875

This site is not affiliated with any of the contributors.