ruby
class Order < ApplicationRecord
  include TransactionalEnqueue

  belongs_to :customer
  has_many :line_items, dependent: :destroy

Transaction-Safe After-Commit Hook (Avoid Ghost Jobs)

rails activerecord background-jobs
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  has_many :comments, dependent: :destroy

  # comments_count is maintained by counter_cache on Comment#belongs_to

  scope :stale_comment_counts, lambda {

Counter Cache Repair Job (Consistency Tooling)

rails activerecord counter-cache
by codesnips 3 tabs
ruby
module KeysetPageable
  extend ActiveSupport::Concern

  included do
    scope :keyset_page, ->(cursor: nil, per: 20) do
      per = per.to_i.clamp(1, 100)

Safe Pagination with Keyset (No OFFSET)

rails activerecord performance
by codesnips 3 tabs
yaml
production:
  primary:
    adapter: postgresql
    database: app_production
    username: app
    password: <%= ENV["PRIMARY_DB_PASSWORD"] %>

Read Replica Routing for GET-Heavy Endpoints

rails activerecord postgres
by codesnips 4 tabs
ruby
class CheckoutService
  def initialize(cart:, user:)
    @cart = cart
    @user = user
  end

Instrument a Service with Notifications

rails observability instrumentation
by codesnips 3 tabs
ruby
class Current < ActiveSupport::CurrentAttributes
  attribute :user, :tenant, :request_id, :ip_address

  def user_display
    user&.email || "system"
  end

CurrentAttributes for Request-Scoped Context

rails activesupport currentattributes
by codesnips 4 tabs
ruby
require "faraday"
require "faraday/retry"

module Http
  class RetryableError < StandardError; end
  class CircuitOpenError < StandardError; end

HTTP Timeouts + Retries Wrapper (Faraday)

rails http reliability
by codesnips 3 tabs
ruby
module Cacheable
  extend ActiveSupport::Concern

  def cache_query(prefix, scope, expires_in: 15.minutes)
    key = [prefix, cache_version_token(scope)].join("/")

Targeted Query Caching for Expensive Endpoints

rails activerecord performance
by codesnips 3 tabs
ruby
class ArticlesController < ApplicationController
  def index
    # Bounded queries: without preload, article.author in the view raises.
    @articles = Article
      .published
      .preload(:author, :tags)

Strict Loading to Catch N+1 in Development

rails activerecord performance
by codesnips 4 tabs
ruby
class AddUniqueIndexToInventorySnapshots < ActiveRecord::Migration[7.1]
  disable_ddl_transaction!

  def change
    add_index :inventory_snapshots,
              [:warehouse_id, :sku],

Bulk Upsert with insert_all + Unique Index

rails activerecord postgres
by codesnips 3 tabs
ruby
class CreateProcessedEvents < ActiveRecord::Migration[7.1]
  def change
    create_table :processed_events do |t|
      t.string :event_key, null: false
      t.string :job_class, null: false
      t.jsonb :metadata, null: false, default: {}

Idempotent Job with Advisory Lock

rails postgres reliability
by codesnips 3 tabs
ruby
class CreateOutboxEvents < ActiveRecord::Migration[7.1]
  def change
    create_table :outbox_events do |t|
      t.string :event_type, null: false
      t.string :aggregate_type, null: false
      t.string :aggregate_id, null: false

Transactional Outbox for Reliable Event Publishing

rails background-jobs reliability
by codesnips 4 tabs