module ExistenceChecks
extend ActiveSupport::Concern
class_methods do
def has_any?(conditions = {})
relation = conditions.present? ? where(conditions) : all
relation.select(Arel.sql('1')).limit(1).exists?
end
def exists_efficiently?(conditions = {})
where(conditions).exists?
end
def pluck_exists(conditions = {})
sql = where(conditions).select(Arel.sql('1')).limit(1).to_sql
connection.select_value("SELECT EXISTS(#{sql})") == true
end
end
end
class Coupon < ApplicationRecord
include ExistenceChecks
has_many :redemptions
scope :active, -> { where('expires_at > ?', Time.current) }
def redeemed_by?(user)
redemptions.exists_efficiently?(user_id: user.id)
end
def slots_available?
return true if max_redemptions.nil?
redemptions.count < max_redemptions
end
end
class EligibilityService
def initialize(user, coupon)
@user = user
@coupon = coupon
end
def can_redeem?
coupon_active? &&
!already_redeemed? &&
user_verified? &&
@coupon.slots_available?
end
private
def coupon_active?
Coupon.active.has_any?(id: @coupon.id)
end
def already_redeemed?
@coupon.redeemed_by?(@user)
end
def user_verified?
@user.identity_documents.exists_efficiently?(status: 'approved')
end
end
-- exists_efficiently?(user_id: 42) generates:
SELECT 1 AS one
FROM redemptions
WHERE redemptions.coupon_id = 7
AND redemptions.user_id = 42
LIMIT 1;
-- pluck_exists wraps it so a plain boolean comes back:
SELECT EXISTS(
SELECT 1
FROM redemptions
WHERE redemptions.coupon_id = 7
AND redemptions.user_id = 42
LIMIT 1
);
Existence checks are one of the most common queries in a web app: does this user have an unread notification, has this order already shipped, is this coupon still valid. A naive Model.where(...).count > 0 or loading the full record wastes work because the database materializes rows or computes a full aggregate when the only fact needed is whether at least one row exists. The idiomatic answer is a query that selects a constant and stops at the first match: SELECT 1 FROM ... WHERE ... LIMIT 1. This snippet shows how that pattern is wrapped into a reusable Rails concern and then consumed by a service object.
In ExistenceChecks concern, the has_any? scope-like class method builds a relation, applies select(Arel.sql('1')) and limit(1), and asks the connection for a single value. Selecting the literal 1 means the database never has to read column data or visit the heap for the projected values; combined with LIMIT 1 the planner can short-circuit on the first qualifying index entry. exists_efficiently? delegates to ActiveRecord's built-in exists?, which already emits SELECT 1 ... LIMIT 1, but the concern also exposes pluck_exists for cases where a raw boolean from SELECT EXISTS(...) is preferable inside a larger query.
The reason count is avoided is subtle: on Postgres a COUNT(*) with a filter must scan every matching row even when the answer is only ever compared to zero. exists? instead asks the planner for the cheapest path to a single tuple, which an index can satisfy immediately. The trade-off is that exists? fires an extra query rather than reusing an already-loaded association, so it is wrong to call it in a loop over records that were eager-loaded — that reintroduces N+1 queries.
In EligibilityService, can_redeem? composes several of these checks and relies on short-circuit boolean evaluation so the most selective, cheapest check runs first and later queries are skipped entirely once one fails. The raw SQL tab shows exactly what Postgres receives and why the LIMIT 1 matters for the index scan. A developer reaches for this pattern whenever the code only needs a yes/no answer and correctness does not depend on the exact count.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
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
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
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
Share this code
Here's the card — post it anywhere.