activerecord

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
ruby
class Document < ApplicationRecord
  belongs_to :account

  validates :source_url, presence: true

  before_save :normalize_checksum

Prevent Long Transactions with after_save_commit for Heavy Work

rails activerecord background-jobs
by codesnips 3 tabs
ruby
class Order < ApplicationRecord
  belongs_to :customer

  scope :for_export, -> {
    select(:id, :reference, :total_cents, :currency, :created_at, :customer_id)
      .where.not(exported_at: nil)

Avoid Memory Blowups: find_each + select Columns

rails activerecord performance
by codesnips 3 tabs
ruby
class CreateSubscriptions < ActiveRecord::Migration[7.1]
  STATUSES = %w[pending active past_due canceled].freeze

  def change
    create_table :subscriptions do |t|
      t.references :account, null: false, foreign_key: true

Schema-Backed Enums (DB Constraint + Rails enum)

rails postgres schema
by codesnips 3 tabs
ruby
class Category < ApplicationRecord
  has_many :products, dependent: :restrict_with_error
  has_many :subcategories,
           class_name: "Category",
           foreign_key: :parent_id,
           dependent: :restrict_with_error

Safer Deletion with dependent: :restrict_with_error

rails activerecord data-integrity
by codesnips 4 tabs
ruby
class UserSearchQuery
  def initialize(relation = User.all)
    @relation = relation
  end

  def call(params)

Query objects for complex database queries

ruby rails query-objects
by Sarah Mitchell 2 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
class TransferFundsService
  def initialize(from_account:, to_account:, amount:)
    @from_account = from_account
    @to_account = to_account
    @amount = amount
  end

Database transactions for data consistency

rails database activerecord
by Alex Kumar 1 tab
ruby
class CreateStripeEvents < ActiveRecord::Migration[7.1]
  def change
    create_table :stripe_events do |t|
      t.string :stripe_event_id, null: false
      t.string :event_type, null: false
      t.string :status, null: false, default: "received"

Idempotent Stripe Webhook Processing in Rails with a Durable Event Log

rails stripe webhooks
by codesnips 4 tabs
ruby
module StatementTimeout
  extend ActiveSupport::Concern

  class TimeoutExceeded < StandardError; end

  def with_statement_timeout(milliseconds)

Guard Against Slow Queries with statement_timeout

rails postgres performance
by codesnips 3 tabs
ruby
module DangerousAction
  extend ActiveSupport::Concern

  FRESH_WINDOW = 10.minutes

  class ConfirmationMismatch < StandardError; end

Guard Rails for Dangerous Admin Actions

rails admin security
by codesnips 3 tabs
ruby
require "loofah"

class HtmlSanitizer
  ALLOWED_TAGS  = %w[p br a strong em ul ol li blockquote code pre h2 h3].freeze
  ALLOWED_ATTRS = %w[href title].freeze
  SAFE_SCHEMES  = %w[http https mailto].freeze

Safer HTML Sanitization Pipeline

rails security xss
by codesnips 4 tabs