oop-query-objects
Installation
SKILL.md
Query Objects
What it is
A Query Object encapsulates a complex or reusable database query in a plain Ruby class. It accepts filters/parameters, builds an ActiveRecord relation, and returns it — staying composable with other scopes and relations.
Query objects are the right home for:
- Multi-join, multi-filter queries that don't belong to a single scope
- Report or analytics queries (aggregations, groupings)
- Filter pipelines (search + sort + paginate with many optional params)
Would a scope do?
Scopes are the default. Extract a query object when:
- A scope exceeds ~10 lines or chains 5+ conditions
- The query needs to accept many optional parameters (a filter form's params)
- The same complex join is copied across multiple scopes
- You're building a query that aggregates across models with no natural owner