Query Objects are useful to extract ActiveRecord scopes or complex SQL queries into their own classes, which would otherwise clutter ActiveRecord models.
- Queries go under the
app/queriesdirectory. - Query class name should have suffix
Query(e.g.AuthorsQuery). - Query class name should start with primary model name used in query in plural form (e.g.
AuthorsWithBooksQuery). - Consider creating base query class for the model (e.g.
AuthorsQuery) and subclasses for more specific cases (e.g.AuthorsWithBooksQuery < AuthorsQuery). - Query object should return
ActiveRecord::Relationobject. - Use scope
nonefor the cases when respond with empty collection is required. - Define only one public method
#perform. - Use auxiliary_rails gem.