Class: ArticleRelation
- Inherits:
-
Cybertrain::Relation
- Object
- Cybertrain::Relation
- ArticleRelation
- Defined in:
- docs/api/stubs/generated_app.rb
Overview
The relation spin run gen writes next to each model (ArticleRelation
for Article): the chainable query methods and the methods that load
records. Start one with Article.all or a shortcut such as
Article.where. The chain methods change this relation and return it;
#dup copies it first when several queries start from one base.
Instance Method Summary collapse
-
#column_type(name) ⇒ Symbol
The schema type of a column:
:integer("id"included),:float,:decimal,:boolean,:datetime,:date,:json,:binary,:stringor:text;:unknownfor a name that is not a column. -
#decimal_scale(name) ⇒ Integer
A decimal column’s
scale:; -1 for any other column or a decimal declared without one. -
#destroy_all ⇒ Array<Article>
Loads the matching records and calls destroy on each, so the destroy callbacks run (one DELETE per record; use delete_all for one statement).
-
#distinct ⇒ self
SELECT DISTINCT: the column readers return each value once (distinct.pluck_str(:kind),ids). -
#dup ⇒ ArticleRelation
An independent copy of this relation, of the same class: the same conditions and binds, order, limit, offset,
distinct,none,having_sqlandincludes, in Arrays of its own, so a chain method called on either afterwards leaves the other as it was. -
#each {|article| ... } ⇒ Object
to_a.each. -
#empty? ⇒ Boolean
Whether the #preloaded records are none, else
!exists?. -
#find(id) ⇒ Article
The record with this id within the relation.
-
#find_by(conditions) ⇒ Article?
where(conditions).first. -
#find_by!(conditions) ⇒ Article
#find_by, raising when nothing matches.
-
#find_each(batch: 1000) {|article| ... } ⇒ nil
Yields every matching record, loading
batchrows at a time (id > last_id ORDER BY id LIMIT batch), so a large table is walked without loading it whole. -
#find_or_create_by(conditions) ⇒ Article
#find_by, or else Article.create with the same attributes.
-
#find_or_initialize_by(conditions) ⇒ Article
#find_by, or else an unsaved Article.new with the same attributes.
-
#first ⇒ Article?
The first record by the relation’s order (by id when it has none), from the #offset on.
-
#having_sql(sql, binds = []) ⇒ self
A HAVING clause for the grouped readers (count_by, sum_float_by, average_by, …), in parentheses and ANDed onto an earlier one; its values bind through
?. -
#includes(*names) ⇒ ArticleRelation
Preloads the named associations when #to_a (or #each) loads the records: one more query per association (
Comment.where(article_id: ids)for a has_many or has_one,User.where(id: author_ids)for a belongs_to, the ids split into chunks of Cybertrain::DB::Connection#variable_limit when there are more), its rows handed to each record’s reader, soarticle.comments.sizeorcomment.articlein a loop runs no query of its own; a record with no child gets an empty list, a missing parent nil. -
#last ⇒ Article?
Without a limit or offset, the first record of the reversed order (the highest id when there is no order); with them, the last record of that window.
-
#limit(n) ⇒ self
-
#none ⇒ self
A relation that matches no row:
count,exists?,update_allanddelete_allanswer 0 / false without a query, the readers are empty. -
#not(conditions) ⇒ self
The negation of #where’s Hash form, AND-ed with the other conditions:
NOT (a AND b)over the termswherewould write (Rails 6.1+). -
#offset(n) ⇒ self
-
#or(other) ⇒ self
Rows matching this relation’s conditions or the other’s: one
((a) OR (b))term. -
#order(order) ⇒ self
Sets the order, replacing any earlier one.
-
#order_sql(sql) ⇒ self
Sets a raw ORDER BY fragment, replacing any earlier order.
-
#preload(*names) ⇒ ArticleRelation
Same as #includes (there is no JOIN strategy to choose between).
-
#preloaded(records) ⇒ ArticleRelation
The relation answers
to_a,each,first,last,sizeandempty?fromrecordsuntil a chain method changes it: what a has_many reader returns after #includes. -
#size ⇒ Integer
The number of #preloaded records, else the same as count.
-
#to_a ⇒ Array<Article>
Runs the query, then the #includes queries.
-
#where(cond = nil, *binds) ⇒ self
Adds conditions, AND-ed with any already there.
-
#where_between(column, from, to, exclude_end: false) ⇒ self
A bounded range on one column:
`col` >= ? AND `col` <= ?(<withexclude_end: true), either bound nil for an open end. -
#where_like(column, text) ⇒ self
Adds a substring match on one column, AND-ed with the others:
`col` LIKE ? ESCAPE '\'with%text%bound, the text’s\,%and_escaped (Cybertrain::Cast.like_escape), so a search box’s input is matched literally. -
#where_sql(sql, binds = []) ⇒ self
Adds a raw SQL condition with
?placeholders, AND-ed with the others.
Methods inherited from Cybertrain::Relation
#average, #average_by, #average_sql, #count, #count_by, #count_by_sql, #delete_all, #exists?, #ids, #increment, #maximum_float, #maximum_float_by, #maximum_float_sql, #maximum_int, #maximum_int_by, #maximum_time, #maximum_time_by, #minimum_float, #minimum_float_by, #minimum_float_sql, #minimum_int, #minimum_int_by, #minimum_time, #minimum_time_by, #page, #pick, #pluck, #pluck_float, #pluck_int, #pluck_str, #sum_float, #sum_float_by, #sum_float_sql, #sum_int, #sum_int_by, #to_sql, #update_all, #update_all_sql
Instance Method Details
#column_type(name) ⇒ Symbol
The schema type of a column: :integer ("id" included), :float,
:decimal, :boolean, :datetime, :date, :json, :binary,
:string or :text; :unknown for a name that is not a column.
489 |
# File 'docs/api/stubs/generated_app.rb', line 489 def column_type(name) = :unknown |
#decimal_scale(name) ⇒ Integer
A decimal column’s scale:; -1 for any other column or a decimal
declared without one.
496 |
# File 'docs/api/stubs/generated_app.rb', line 496 def decimal_scale(name) = -1 |
#destroy_all ⇒ Array<Article>
Loads the matching records and calls destroy on each, so the destroy callbacks run (one DELETE per record; use delete_all for one statement).
789 |
# File 'docs/api/stubs/generated_app.rb', line 789 def destroy_all; end |
#distinct ⇒ self
SELECT DISTINCT: the column readers return each value once
(distinct.pluck_str(:kind), ids). A row of SELECT * carries its
id, so every row is distinct and count
(and to_a) of a distinct relation is the same as without it.
640 |
# File 'docs/api/stubs/generated_app.rb', line 640 def distinct = (set_distinct; self) |
#dup ⇒ ArticleRelation
An independent copy of this relation, of the same class: the same
conditions and binds, order, limit, offset, distinct, none,
having_sql and includes, in Arrays of its own, so a chain method
called on either afterwards leaves the other as it was. Nothing runs:
the copy is as lazy as its source. Use it to start several queries
from one base, because the chain methods change their receiver:
base = Article.where("created_at >= ?", since)
newest = base.dup.order(created_at: :desc).limit(5).to_a
titled = base.dup.where_like(:title, "spinel").count
# base is still only `created_at >= ?`
Without dup, newest and titled would be base itself, and the
second query would carry the first one’s order and limit. A copy of a
#preloaded relation (a has_many reader after #includes) answers
from an Array of its own holding the same records, until a chain
method changes it. The records themselves are not copied. Cybertrain::Relation#page
windows the relation it is called on, so base.dup.page(...) leaves
base unwindowed.
724 |
# File 'docs/api/stubs/generated_app.rb', line 724 def dup; end |
#each {|article| ... } ⇒ Object
to_a.each.
739 |
# File 'docs/api/stubs/generated_app.rb', line 739 def each(&blk) = to_a.each(&blk) |
#empty? ⇒ Boolean
Whether the #preloaded records are none, else !exists?.
821 |
# File 'docs/api/stubs/generated_app.rb', line 821 def empty?; end |
#find(id) ⇒ Article
The record with this id within the relation.
810 |
# File 'docs/api/stubs/generated_app.rb', line 810 def find(id); end |
#find_by(conditions) ⇒ Article?
where(conditions).first. Like every chain method, it narrows this
relation itself.
761 |
# File 'docs/api/stubs/generated_app.rb', line 761 def find_by(conditions) = where(conditions).first |
#find_by!(conditions) ⇒ Article
#find_by, raising when nothing matches.
768 |
# File 'docs/api/stubs/generated_app.rb', line 768 def find_by!(conditions); end |
#find_each(batch: 1000) {|article| ... } ⇒ nil
Yields every matching record, loading batch rows at a time
(id > last_id ORDER BY id LIMIT batch), so a large table is walked
without loading it whole. Records come in id order; the relation’s own
order, limit and offset are not used.
801 |
# File 'docs/api/stubs/generated_app.rb', line 801 def find_each(batch: 1000, &blk); end |
#find_or_create_by(conditions) ⇒ Article
#find_by, or else Article.create with the same attributes.
776 |
# File 'docs/api/stubs/generated_app.rb', line 776 def find_or_create_by(conditions); end |
#find_or_initialize_by(conditions) ⇒ Article
#find_by, or else an unsaved Article.new with the same attributes.
782 |
# File 'docs/api/stubs/generated_app.rb', line 782 def find_or_initialize_by(conditions); end |
#first ⇒ Article?
The first record by the relation’s order (by id when it has none), from the #offset on. A #preloaded relation answers its first preloaded record (preloaded children come in id order) without a query.
746 |
# File 'docs/api/stubs/generated_app.rb', line 746 def first; end |
#having_sql(sql, binds = []) ⇒ self
A HAVING clause for the grouped readers
(count_by,
sum_float_by,
average_by, …), in parentheses and
ANDed onto an earlier one; its values bind through ?. Every other
reader of a relation with a HAVING raises ArgumentError rather than
drop it, and so does a grouped reader under a limit or offset. The
text is trusted SQL, like #order_sql’s: never build it from request
data.
664 |
# File 'docs/api/stubs/generated_app.rb', line 664 def having_sql(sql, binds = []) = (set_having_sql(sql, binds); self) |
#includes(*names) ⇒ ArticleRelation
Preloads the named associations when #to_a (or #each) loads the
records: one more query per association (Comment.where(article_id:
ids) for a has_many or has_one, User.where(id: author_ids) for a
belongs_to, the ids split into chunks of
Cybertrain::DB::Connection#variable_limit when there are more), its
rows handed to each record’s reader, so article.comments.size or
comment.article in a loop runs no query of its own; a record with no
child gets an empty list, a missing parent nil. One level only; the
other readers (count, pluck, first,
…) ignore it. With no names it does nothing.
683 |
# File 'docs/api/stubs/generated_app.rb', line 683 def includes(*names); end |
#last ⇒ Article?
Without a limit or offset, the first record of the reversed order (the highest id when there is no order); with them, the last record of that window. A #preloaded relation answers its last preloaded record without a query.
754 |
# File 'docs/api/stubs/generated_app.rb', line 754 def last; end |
#limit(n) ⇒ self
627 |
# File 'docs/api/stubs/generated_app.rb', line 627 def limit(n) = (set_limit(n); self) |
#none ⇒ self
A relation that matches no row: count, exists?, update_all and
delete_all answer 0 / false without a query, the readers are empty.
646 |
# File 'docs/api/stubs/generated_app.rb', line 646 def none = (set_none; self) |
#not(conditions) ⇒ self
The negation of #where’s Hash form, AND-ed with the other conditions:
NOT (a AND b) over the terms where would write (Rails 6.1+). So
where.not(body: nil) is NOT (body IS NULL), where.not(id: [])
matches every row, and where.not(kind: "a") leaves out NULL kinds,
as SQL’s != does.
540 |
# File 'docs/api/stubs/generated_app.rb', line 540 def not(conditions) = (add_where_not(conditions); self) |
#offset(n) ⇒ self
632 |
# File 'docs/api/stubs/generated_app.rb', line 632 def offset(n) = (set_offset(n); self) |
#or(other) ⇒ self
Rows matching this relation’s conditions or the other’s: one
((a) OR (b)) term. A side with no conditions matches every row.
565 |
# File 'docs/api/stubs/generated_app.rb', line 565 def or(other) = (merge_or(other); self) |
#order(order) ⇒ self
Sets the order, replacing any earlier one. Takes only comma-separated
column [ASC|DESC] terms (a Symbol is a column name; nil or ""
removes the order). Request data must go through an allowlist first,
since even a well-formed term can name a column the client must not
sort by.
612 |
# File 'docs/api/stubs/generated_app.rb', line 612 def order(order); end |
#order_sql(sql) ⇒ self
Sets a raw ORDER BY fragment, replacing any earlier order. Never pass
request data. #last reverses it by flipping ASC/DESC around commas,
which can mangle text such as COALESCE(a, b).
622 |
# File 'docs/api/stubs/generated_app.rb', line 622 def order_sql(sql) = (add_order_sql(sql); self) |
#preload(*names) ⇒ ArticleRelation
Same as #includes (there is no JOIN strategy to choose between).
688 |
# File 'docs/api/stubs/generated_app.rb', line 688 def preload(*names) = includes(*names) |
#preloaded(records) ⇒ ArticleRelation
The relation answers to_a, each, first, last, size and
empty? from records until a chain method changes it: what a
has_many reader returns after #includes. count and exists? still
query.
697 |
# File 'docs/api/stubs/generated_app.rb', line 697 def preloaded(records); end |
#size ⇒ Integer
The number of #preloaded records, else the same as count.
816 |
# File 'docs/api/stubs/generated_app.rb', line 816 def size; end |
#to_a ⇒ Array<Article>
Runs the query, then the #includes queries. Templates iterate an
Array, so controllers usually end a query with to_a. A
#preloaded relation answers a new Array of its records (changing it
leaves the association as it was).
734 |
# File 'docs/api/stubs/generated_app.rb', line 734 def to_a; end |
#where(cond = nil, *binds) ⇒ self
Adds conditions, AND-ed with any already there. With a Hash, keys are SQL column names and values are bound, never interpolated:
| Value | SQL |
|---|---|
nil |
`col` IS NULL |
| an Array | `col` IN (?, ?) (an empty Array matches nothing) |
an Integer Range 1..5 |
`col` BETWEEN ? AND ? |
1...5, 5.., ..5 |
`col` >= ? AND `col` < ?, `col` >= ?, `col` <= ? |
| a Time | `col` = ? with the stored datetime text |
true / false |
`col` = ? with 1 / 0 |
| anything else | `col` = ? |
A Range takes Integer ends only; other bounds (Time, Date, Float,
String) go through #where_between. A json column cannot be compared
(ArgumentError). With a String, it is a raw SQL condition with ?
placeholders and the binds after it, as #where_sql, wrapped in
parentheses so an OR in it stays inside; an Array bind raises (use the
Hash form for IN). With no argument it is the relation itself, so
where.not(...) reads as in Rails; any other argument raises.
528 |
# File 'docs/api/stubs/generated_app.rb', line 528 def where(cond = nil, *binds); end |
#where_between(column, from, to, exclude_end: false) ⇒ self
A bounded range on one column: `col` >= ? AND `col` <= ? (< with
exclude_end: true), either bound nil for an open end. A Time or Date
bound is compared as the stored text, which orders as the instant does.
554 |
# File 'docs/api/stubs/generated_app.rb', line 554 def where_between(column, from, to, exclude_end: false) = (add_where_between(column, from, to, exclude_end); self) |
#where_like(column, text) ⇒ self
Adds a substring match on one column, AND-ed with the others:
`col` LIKE ? ESCAPE '\' with %text% bound, the text’s \, %
and _ escaped (Cybertrain::Cast.like_escape), so a search box’s
input is matched literally. Case-insensitive for ASCII, as SQLite’s
LIKE is; NULL never matches. A prefix search writes its own pattern
through #where_sql.
594 |
# File 'docs/api/stubs/generated_app.rb', line 594 def where_like(column, text) = (add_where_like(column, text); self) |
#where_sql(sql, binds = []) ⇒ self
Adds a raw SQL condition with ? placeholders, AND-ed with the others.
The fragment is used as written, in parentheses: never build it from
request data; pass values as binds (one value per ?; an Array bind
raises ArgumentError).
577 |
# File 'docs/api/stubs/generated_app.rb', line 577 def where_sql(sql, binds = []) = (add_where_sql(sql, binds); self) |