Skip to content

Instantly share code, notes, and snippets.

View mattstenback's full-sized avatar

Matthew Stenback mattstenback

View GitHub Profile
class ActiveRecord::Relation
# Preload one level a chained association whose name is specified in attribute.
def preload_chain(attribute, collection: nil)
preloader = ActiveRecord::Associations::Preloader.new
preloader.preload(collection || records, attribute.to_sym)
self
end
# Preload all levels of a chained association specified in attribute. Will cause infinite loops if there are cycles.
def deep_preload_chain(attribute, collection: nil)

Transactions

As your business logic gets complex you may need to implement transactions. The classic example is a bank funds transfer from account A to account B. If the withdrawal from account A fails then the deposit to account B should either never take place or be rolled back.

Basics

All the complexity is handled by ActiveRecord::Transactions. Any model class or instance has a method named .transaction. When called and passed a block, that block will be executed inside a database transaction. If there's an exception raised, the transaction will automatically be rolled back.

Example