activerecord

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 AddSoftDeleteToDocuments < ActiveRecord::Migration[7.0]
  disable_ddl_transaction!

  def change
    add_column :documents, :marked_for_deletion_at, :datetime, null: true

Safer Time-Based Deletes with “mark then sweep”

rails reliability activerecord
by codesnips 4 tabs
ruby
class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :author, class_name: "User"

  validates :body, presence: true, length: { maximum: 5_000 }

Declarative model broadcasts with broadcasts_to (Rails 7)

rails hotwire turbo
by codesnips 4 tabs
ruby
module ConnectionHealth
  extend ActiveSupport::Concern

  def with_fresh_connection
    conn = ActiveRecord::Base.connection
    conn.verify! # pings and reconnects if the socket is dead

Keep DB Connections Healthy in Long Jobs

rails activerecord background-jobs
by codesnips 3 tabs
ruby
class Order < ApplicationRecord
  has_many :line_items, dependent: :destroy, inverse_of: :order

  accepts_nested_attributes_for :line_items,
    reject_if: :all_blank,
    allow_destroy: true

Transactionally Create Parent + Children with accepts_nested_attributes_for

rails activerecord nested-attributes
by codesnips 3 tabs
ruby
class Current < ActiveSupport::CurrentAttributes
  attribute :tenant, :request_id

  def tenant=(tenant)
    super
    Rails.logger.tagged("tenant=#{tenant&.id}") if tenant

Tenant Isolation in Rails with CurrentAttributes and an around_action

rails multi-tenancy current-attributes
by codesnips 4 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 CreateAuditLogs < ActiveRecord::Migration[7.1]
  def change
    create_table :audit_logs do |t|
      t.references :auditable, polymorphic: true, null: false
      t.references :user, null: true, foreign_key: true
      t.string :action, null: false

Rails Audit Log for Model Changes Using ActiveRecord Callbacks

rails activerecord callbacks
by codesnips 4 tabs
ruby
class Order < ApplicationRecord
  has_many :line_items, inverse_of: :order, dependent: :destroy

  accepts_nested_attributes_for :line_items,
    allow_destroy: true,
    reject_if: ->(attrs) { attrs["product_id"].blank? && attrs["quantity"].blank? }

Validate Nested Attributes for an Order and Its Line Items in Rails

rails activerecord validations
by codesnips 3 tabs
ruby
class OverdueInvoicesQuery
  def initialize(relation: Invoice.all, as_of: Time.current)
    @relation = relation
    @as_of = as_of
  end

ActiveRecord::Relation as a Boundary (No Arrays)

rails activerecord query-objects
by codesnips 3 tabs
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
module DomainEvents
  class Registry
    def initialize
      @subscribers = Hash.new { |h, k| h[k] = [] }
    end

Avoid Callback Chains: Use Domain Events (In-App)

rails architecture domain-events
by codesnips 4 tabs