activerecord

ruby
class AddDeletedAtToPosts < ActiveRecord::Migration[6.1]
  def change
    add_column :posts, :deleted_at, :datetime
    add_index :posts, :deleted_at
  end
end

Soft deletes with paranoia gem

rails activerecord database
by Alex Kumar 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 Document < ApplicationRecord
  belongs_to :owner, class_name: "User"
  has_many :visibilities, class_name: "DocumentVisibility", dependent: :delete_all

  scope :public_documents, -> { where(is_public: true) }

Polymorphic “Visible To” Scope with Arel

rails activerecord arel
by codesnips 3 tabs
ruby
class CreateInventoryReservations < ActiveRecord::Migration[7.1]
  def change
    create_table :inventory_items do |t|
      t.string  :sku, null: false
      t.integer :quantity_on_hand,  null: false, default: 0
      t.integer :quantity_reserved, null: false, default: 0

Transactional “Reserve Inventory” with SELECT … FOR UPDATE

rails activerecord transactions
by codesnips 3 tabs
ruby
module Api
  module V1
    class PostsController < BaseController
      def index
        # Eager load author and recent comments with their authors
        posts = Post.published

N+1 prevention with includes and preload

rails activerecord performance
by Alex Kumar 1 tab
ruby
module Middleware
  class DatabasePinning
    PIN_WINDOW = 5.seconds

    def initialize(app)
      @app = app

“Read Your Writes” Consistency: Pin to Primary After POST

rails consistency reliability
by codesnips 4 tabs
ruby
module WriteAmplificationGuard
  extend ActiveSupport::Concern

  def update_if_changed(attrs)
    changed = attrs.each_with_object({}) do |(key, value), acc|
      cast = self.class.type_for_attribute(key.to_s).cast(value)

“Write Amplification” Guard: Only Update Changed Columns

rails activerecord performance
by codesnips 3 tabs
ruby
class DocumentsController < ApplicationController
  before_action :set_document, only: :destroy

  def destroy
    @document.discard!

Undo delete with a Turbo Stream “restore” action

rails hotwire turbo-streams
by codesnips 4 tabs
ruby
class CreateTags < ActiveRecord::Migration[7.0]
  def change
    create_table :tags do |t|
      t.string :name, null: false
      t.integer :taggings_count, null: false, default: 0
      t.timestamps

Normalize Tags at Write Time

rails activerecord callbacks
by codesnips 3 tabs
ruby
# Create table migration
class CreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      t.string :email, null: false, index: { unique: true }
      t.string :name, null: false

Database migrations and schema management

ruby rails migrations
by Sarah Mitchell 2 tabs
ruby
class AddOptimisticLockingToDocuments < ActiveRecord::Migration[7.1]
  def change
    add_column :documents, :lock_version, :integer, null: false, default: 0
    add_index :documents, :updated_at
  end
end

Optimistic Locking for Collaborative Edits

rails activerecord concurrency
by codesnips 3 tabs
ruby
module CollectionCacheKey
  extend ActiveSupport::Concern

  def cache_key_for(scope)
    relation = scope.respond_to?(:all) ? scope.all : scope
    model = relation.klass

Deterministic Cache Keys for Collections

rails caching activerecord
by codesnips 3 tabs