Aggregation and Selection
Beyond filtering, relations expose set-shaping operations: deduplication, grouping, subquery sources, and per-relation flags.
distinct
distinct adds SELECT DISTINCT. Applies across all selected columns.
1 2 3 | |
distinct(False) clears the flag again. unscope(:distinct) does the same.
1 2 | |
sum, average, minimum, maximum
These return a scalar across the relation. NULLs are ignored; sum on an
empty relation returns 0, and the others return Nil.
1 2 3 4 5 6 7 8 | |
When the relation has joins, bare column names are auto-qualified with the
base table. Pass "games.year" or any other qualified form explicitly to
override.
calculate
calculate($op, $col?) dispatches to the right aggregate by name. $op is
case-insensitive and accepts sum, avg/average, min/minimum,
max/maximum, and count. count is the only operation where $col is
optional.
1 2 3 4 | |
count
count returns an Int for an ungrouped relation. With a column, it
counts non-NULL rows; combined with distinct, it counts distinct
non-NULLs.
1 2 3 | |
For a grouped relation, see below.
group and having
group(*@cols) adds GROUP BY. having(...) adds a HAVING clause. The
raw form accepts a SQL fragment with positional binds; the hash form is
Rails-style and works on aggregates or grouped columns.
1 2 3 4 5 6 7 8 9 | |
Other aggregates on a grouped relation return a hash keyed by the group value:
1 2 3 4 5 6 | |
regroup(*@cols) replaces any prior group clause. unscope(:group) and
unscope(:having) drop the respective clause.
1 2 | |
pluck of SQL expressions
pluck accepts a bare column name or an arbitrary SQL expression. An entry
is treated as an expression (no auto-qualification) when it contains a
parenthesis, a dot, or whitespace.
1 2 3 | |
from
from($source [, $alias]) replaces the implicit FROM table_name. Use it
for subqueries or aliased base tables.
1 2 3 4 5 6 | |
unscope(:from) resets to the default table.
readonly
A readonly relation produces records that refuse to save / update /
destroy. Useful when a query crosses join tables and the records should not
be persisted back.
1 2 | |
merge propagates the flag:
1 | |
extending
extending(*@modules) mixes additional methods into the relation. Useful
for paginators or custom finders local to a query chain.
1 2 3 4 5 6 7 8 | |
You can pass multiple modules; their methods compose in declaration order.
1 2 3 4 5 | |