activerecord

ruby
require 'activerecord-import'

class BulkImportPostsService
  BATCH_SIZE = 1000

  def initialize(csv_file_path)

Bulk operations with ActiveRecord import

rails performance activerecord
by Alex Kumar 1 tab
ruby
module QueryBudget
  class Counter
    IGNORED = %w[SCHEMA CACHE TRANSACTION].freeze

    attr_reader :count

Per-Request Query Budget (Detect Runaway Pages)

rails performance observability
by codesnips 4 tabs
ruby
class AddSearchVectorToArticles < ActiveRecord::Migration[7.1]
  def up
    execute <<~SQL
      ALTER TABLE articles
      ADD COLUMN search_vector tsvector
      GENERATED ALWAYS AS (

Multi-Column Full Text Search with tsvector

rails postgres search
by codesnips 3 tabs
ruby
class Reminder < ApplicationRecord
  belongs_to :user

  validates :time_zone, inclusion: { in: ActiveSupport::TimeZone::MAPPING.values }
  validates :local_time, presence: true

Time Zone Safe Scheduling

rails timezone scheduling
by codesnips 3 tabs
ruby
class DebouncedReindexJob
  include Sidekiq::Job

  sidekiq_options queue: :indexing, retry: 5

  DEBOUNCE_DELAY = 5 # seconds

Debouncing Sidekiq Jobs Per-Record With Redis So Rapid Updates Coalesce Into One Run

rails sidekiq redis
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 InventoryLevel < ApplicationRecord
  belongs_to :warehouse

  UPSERT_COLUMNS = %w[warehouse_id sku on_hand reserved updated_at].freeze

  def self.upsert_counts(rows)

Bulk-Upsert Inventory Counts in One Query From a Sidekiq Job

rails postgres upsert
by codesnips 3 tabs
ruby
class Order < ApplicationRecord
  class InvalidTransition < StandardError; end

  enum status: { pending: 0, paid: 1, shipped: 2, cancelled: 3 }

  has_many :order_transitions, -> { order(:created_at) }, dependent: :destroy

Order State Machine With Guarded Transitions and an Audit Trail in Rails

rails state-machine activerecord
by codesnips 3 tabs
ruby
class User < ApplicationRecord
  normalizes :phone, with: ->(value) { PhoneNormalizer.call(value) }, apply_to_nil: false

  validates :phone,
            presence: true,
            uniqueness: { case_sensitive: false },

Normalizing Phone Numbers on Assignment with Rails normalizes and a Custom Serializer

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

  validates :body, presence: true

Model broadcasts: prepend on create, replace on update

rails hotwire turbo-streams
by codesnips 4 tabs