Query Objects
The Service Objects guide moves the writes out of your controllers and models. This guide does the same for the reads. A query object is a class that owns one model's non-trivial queries β the filtered listing, the search, the report β with typed, validated arguments and a description of what each query is for. We use ActiveQuery for it: a small DSL over ActiveRecord that returns ordinary relations, so everything you already know about chaining still applies.
1. Why Query Objects
Reads accumulate in two bad places. Controllers grow
where chains that depend on params, and every action that lists the
same thing reinvents them slightly differently. Models grow scopes
until the model file is mostly about how other people search it, and
scopes can't say which arguments they need or what a bad one looks
like.
A query object fixes both. The controller asks one named question β
OrderQuery.overdue(days: 30) β and the answer is a relation it can
paginate, count, or hand to a view. The model keeps its scopes as
vocabulary. And the query class is the one place to read, test, and
change how that question is answered. The pairing with interactions is
deliberate: interactions mutate, queries read, and neither has to
know how the other works.
def index
@orders = Order.where(status: params[:status])
@orders = @orders.where("total > ?", params[:min_total]) if params[:min_total].present?
@orders = @orders.where(customer_id: current_account.customer_ids)
@orders = @orders.order(placed_at: :desc)
enddef index
@orders = OrderQuery.for_account(
account_id: current_account.id,
status: params[:status],
min_total: params[:min_total]
).order(placed_at: :desc)
end2. Installation
Add the gem β note the hyphen; active_query with an underscore is an
unrelated, abandoned gem β and run bundle install. It needs Ruby 3.2+
and ActiveRecord 6.1 through 8.x; there is nothing to generate or
configure.
# Gemfile
gem "active-query", "~> 0.2"Mirror the interactions layout: a base module in app/queries/ that
every query object includes, so shared behaviour has a home later.
ActiveQuery registers classes that include it through an intermediate
concern just as well as direct includes:
# app/queries/application_query.rb
module ApplicationQuery
extend ActiveSupport::Concern
include ActiveQuery::Base
end3. Defining a Query Object
A query object names its model and declares queries with query: a
name, a one-line description, optionally an argument definition,
and a lambda that builds on scope β the model's all relation, with
ActiveQuery's extra operations mixed in. Each query becomes a class
method returning a plain ActiveRecord::Relation:
# app/queries/order_query.rb
class OrderQuery
include ApplicationQuery
model_name "Order"
query :overdue, "Orders past their due date that are still unpaid",
{ days: { type: Integer, default: 0 } },
->(days:) { scope.where(paid_at: nil).lt(:due_on, days.days.ago.to_date) }
query :for_account, "An account's orders, optionally filtered by status and minimum total",
{
account_id: { type: Integer },
status: { type: String, optional: true },
min_total: { type: Float, optional: true }
},
->(account_id:, status:, min_total:) {
scope.where(account_id: account_id)
.if(status.present?, -> { where(status: status) })
.if(min_total.present?, -> { gt(:total, min_total) })
}
endOrderQuery.overdue # => ActiveRecord::Relation
OrderQuery.overdue(days: 30).count
OrderQuery.for_account(account_id: 7, status: "shipped").includes(:customer).limit(20)ActiveQuery infers the model only from a namespaced class named
Query β Orders::Query resolves to Order. The flat OrderQuery
form does not infer (the suffix isn't stripped), and the first query
you call raises "Model not defined". Declaring model_name "Order"
costs one line and works for both spellings, so make it a habit.
4. Arguments
The argument definition is the part a scope can't give you. Each
argument has a type (String, Integer, Float, Boolean, or a
type class you register), and may be optional: true or carry a
default: β never both. Calls are validated before the lambda runs,
and the errors say exactly what went wrong:
OrderQuery.for_account # ArgumentError: Params missing: [:account_id]
OrderQuery.for_account(account_id: 7, foo: 1) # ArgumentError: Unknown params: [:foo]
OrderQuery.for_account(account_id: "seven") # ArgumentError: :account_id must be of type IntegerValues are coerced before they are validated: "7" becomes 7,
"true" becomes true, a symbol becomes a string. That is what lets a
query object take params values directly without a cast at every
call site. Optional arguments arrive as nil, so the lambda's if
guards are how "not given" becomes "not filtered". If you need a type
the gem doesn't know β a UUID, a currency code β subclass
ActiveQuery::Types::Base and register it once in an initializer.
5. Composing Queries
Because every query returns a relation, composition is just chaining:
OrderQuery.overdue.merge(OrderQuery.for_account(account_id: 7)), or
call one query object's result from another's lambda. Inside the
lambdas, three tools keep the code flat:
if/unlessapply a block of conditions only when a test is true β the idiomatic way to handle optional filters.- Comparison and pattern operations β
gt,gteq,lt,lteq,like,start_like,end_likeβ replace the string SQL fragments thatwhereneeds for anything but equality. - A
Scopesmodule inside the query object defines named, reusable pieces available onscope, so a long query reads as a sentence.
class OrderQuery
include ApplicationQuery
model_name "Order"
module Scopes
include ActiveQuery::Scopes
scope :unpaid, -> { where(paid_at: nil) }
scope :placed_since, ->(date:) { gteq(:placed_at, date) }
end
query :recent_unpaid, "Unpaid orders placed in the last month",
-> { scope.unpaid.placed_since(date: 1.month.ago) }
query :search, "Orders whose reference starts with a prefix",
{ prefix: { type: String } },
->(prefix:) { scope.start_like(:reference, prefix) }
endWhen a query outgrows a lambda β joins, grouping, a having clause β
move it to a resolver, a class inheriting from
ActiveQuery::Resolver whose resolve method receives the same
keyword arguments and builds on scope. The query object stays a
readable index of what can be asked; the resolver holds how.
# app/queries/resolvers/top_customers_resolver.rb
class TopCustomersResolver < ActiveQuery::Resolver
def resolve(min_orders: 5)
scope.joins(:orders)
.group("customers.id")
.having("COUNT(orders.id) >= ?", min_orders)
.select("customers.*, COUNT(orders.id) AS order_count")
end
end
class CustomerQuery
include ApplicationQuery
model_name "Customer"
query :top, "Customers with at least min_orders orders",
{ min_orders: { type: Integer } },
resolver: TopCustomersResolver
endOrderQuery.queries returns each query's name, description, and
argument definition, and ActiveQuery::Base.registry lists every
query object in the app. That is enough to generate an admin
"reports" page, a CLI, or documentation from the query layer itself β
and it is why the description argument is required, not decorative.
6. Testing a Query Object
A query object is tested against a real database with a handful of
records β this is what
factories are for. Create the rows
that should match and one that shouldn't, call the query, and assert
on the result. Argument validation gets one example per rule, and a
to_sql assertion is worth it only when the SQL shape is the
behaviour (an index you depend on, a join you must avoid):
# spec/queries/order_query_spec.rb
RSpec.describe OrderQuery do
describe ".overdue" do
it "returns unpaid orders past their due date" do
overdue = create(:order, :unpaid, due_on: 10.days.ago)
create(:order, :unpaid, due_on: 2.days.from_now) # not yet due
create(:order, :paid, due_on: 10.days.ago) # paid, so not overdue
expect(described_class.overdue).to contain_exactly(overdue)
end
it "widens the window with days:" do
create(:order, :unpaid, due_on: 10.days.ago)
expect(described_class.overdue(days: 30)).to be_empty
end
end
describe ".for_account" do
it "requires account_id" do
expect { described_class.for_account }.to raise_error(ArgumentError, /account_id/)
end
end
end7. Scope, Query Object, or Interaction?
Three tools that all "get data" is a recipe for arguments unless the boundaries are stated. Ours:
| You need | Reach for | Why |
|---|---|---|
One predicate on one model that many places need β | Model scope | A scope is the model's vocabulary. Query objects use scopes; they don't replace them. |
A read that takes arguments, has rules about them, or combines several conditions β a filtered listing, a search, a report | Query object | Typed arguments, a description, one place to test, and a relation you can keep chaining. |
Anything that writes β create, update, send, enqueue | Interaction | Reads compose; writes need validation, an outcome, and a transaction boundary. That is the Service Objects guide. |
A one-off | Inline | Extracting a single line into a class is ceremony, not design. Promote it when the second caller shows up. |
The line between the first two is arguments and rules. The moment a scope wants two parameters, a default, or a "but only whenβ¦", it is a query. The line between a query and an interaction is side effects: a query object must never write, enqueue, or send β if it needs to, it was an interaction all along, and the interaction can call the query for its reads.
Success!
Your reads have a home that matches your writes: named, typed, described, and tested in one place. Before you move on: