ruby
14 lines · 1 tab
Alex Kumar
Jan 2026
1 tab
class AddIndexesToPosts < ActiveRecord::Migration[6.1]
def change
add_index :posts, :author_id
add_index :posts, :published_at
add_index :posts, [:author_id, :published_at]
add_index :posts, :created_at, order: { created_at: :desc }
# Partial index for active published posts
add_index :posts, :id, where: 'published_at IS NOT NULL AND deleted_at IS NULL', name: 'index_posts_published_active'
# GIN index for array column tag searches
add_index :posts, :tags, using: :gin
end
end
1 file · ruby
Explain with highlit
Proper indexing is the difference between millisecond and multi-second query response times. I add indexes to foreign keys automatically since Rails doesn't do this by default, and I create composite indexes for common query patterns that filter on multiple columns. The EXPLAIN output guides index decisions—when I see sequential scans on large tables, that's a signal to add an index. Partial indexes are particularly useful for queries that filter on a specific condition frequently, like WHERE deleted_at IS NULL. I also use index: { unique: true } in migrations to enforce data integrity constraints at the database level. Monitoring slow query logs in production reveals which indexes deliver the most value.
Related snips
sql
-- Simple function
CREATE OR REPLACE FUNCTION get_full_name(
first_name VARCHAR,
last_name VARCHAR
)
RETURNS VARCHAR AS $$
Stored procedures and functions in PostgreSQL
postgresql
stored-procedures
functions
by Maria Garcia
2 tabs
ruby
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
rails
hotwire
turbo
by codesnips
4 tabs
ruby
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
rails
activerecord
patterns
by Alex Kumar
1 tab
ruby
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
rails
caching
http-caching
by Alex Kumar
1 tab
ruby
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
rails
turbo
hotwire
by codesnips
4 tabs
ruby
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
rails
performance
streaming
by codesnips
3 tabs
Share this code
Here's the card — post it anywhere.