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) }
scope :recent, -> { order(created_at: :desc) }
scope :by_author, ->(author_id) { where(author_id: author_id) }
scope :tagged_with, ->(tag) { where('tags @> ARRAY[?]::varchar[]', tag) }
def published?
published_at.present? && published_at <= Time.current
end
end
Scopes encapsulate reusable query logic directly in the model, improving code readability and reducing duplication across controllers and services. I use scopes for common filters like active, published, or recent rather than writing raw where clauses everywhere. The chainable nature of scopes makes it easy to compose complex queries from simple building blocks without introducing SQL injection vulnerabilities. I prefer using lambda syntax for scopes that accept parameters to ensure lazy evaluation. When scopes grow complex, I extract them into dedicated query objects, but for straightforward filters, scopes keep the model layer clean and self-documenting. This pattern also makes testing easier since I can verify query logic in model specs independently.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
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
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
<form data-controller="query-sync" data-action="change->query-sync#apply">
<select name="status" class="rounded border p-2">
<option value="">Any</option>
<option value="open">Open</option>
<option value="closed">Closed</option>
</select>
Filter UI that syncs query params via Stimulus (no front-end router)
class SignupForm
include ActiveModel::Model
include ActiveModel::Attributes
attribute :account_name, :string
attribute :email, :string
Shallow Controller, Deep Params: Form Object Pattern
Share this code
Here's the card — post it anywhere.