Class: ArticleRelation

Inherits:
Cybertrain::Relation show all
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.

Examples:

Article.where(title: "Hello").order("created_at DESC").limit(5).to_a
Comment.where(article_id: @article.id).count

Instance Method Summary collapse

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.

Examples:

Article.all.column_type("title") # => :string

Parameters:

  • name (String) —

    the SQL column name

Returns:

  • (Symbol)


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.

Parameters:

  • name (String) —

    the SQL column name

Returns:



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).

Returns:

  • (Array<Article>) —

    the destroyed records



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.

Returns:

  • (self)


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.

Examples:

comments = @article.comments
@recent = comments.dup.order(created_at: :desc).limit(3).to_a
@count = comments.count

Returns:



724
# File 'docs/api/stubs/generated_app.rb', line 724

def dup; end

#each {|article| ... } ⇒ Object

to_a.each.

Yield Parameters:



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?.

Returns:

  • (Boolean)


821
# File 'docs/api/stubs/generated_app.rb', line 821

def empty?; end

#find(id) ⇒ Article

The record with this id within the relation.

Examples:

Comment.where(article_id: @article.id).find(params[:id])

Parameters:

Returns:

Raises:



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.

Parameters:

  • conditions (Hash{Symbol => Object})

Returns:



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.

Parameters:

  • conditions (Hash{Symbol => Object})

Returns:

Raises:



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.

Examples:

Article.where(body: nil).find_each(batch: 500) { |a| a.update_columns(body: "") }

Parameters:

  • batch (Integer) (defaults to: 1000) —

    rows per query, at least 1

Yield Parameters:

Returns:

  • (nil)


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.

Examples:

Tag.find_or_create_by(name: "ruby")

Parameters:

  • conditions (Hash{Symbol => Object})

Returns:



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.

Parameters:

  • conditions (Hash{Symbol => Object})

Returns:



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.

Returns:



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.

Examples:

Reading.all.having_sql("SUM(value) > ?", [2.0]).sum_float_by(:kind, :value)
# => {"a" => 3.0}

Parameters:

  • sql (String) —

    SQL text

  • binds (Array) (defaults to: []) —

    values for its ? placeholders

Returns:

  • (self)


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.

Examples:

@articles = Article.order(created_at: :desc).includes(:comments).to_a
# in the template, @articles.each { |a| a.comments.size } runs no query

Parameters:

  • names (Array<Symbol>) —

    association names of Article

Returns:

Raises:

  • (ArgumentError) —

    "unknown association <name> for Article"



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.

Returns:



754
# File 'docs/api/stubs/generated_app.rb', line 754

def last; end

#limit(n) ⇒ self

Parameters:

  • n (Integer) —

    at most this many rows; 0 returns none

Returns:

  • (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.

Returns:

  • (self)


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.

Examples:

Article.where.not(title: "Draft")

Parameters:

  • conditions (Hash{Symbol => Object})

Returns:

  • (self)


540
# File 'docs/api/stubs/generated_app.rb', line 540

def not(conditions) = (add_where_not(conditions); self)

#offset(n) ⇒ self

Parameters:

Returns:

  • (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.

Examples:

Article.where(title: "Hello").or(Article.where(body: nil))

Parameters:

Returns:

  • (self)

Raises:

  • (ArgumentError) —

    "or: the relations differ in order, limit, offset or distinct"



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.

Examples:

Article.order("created_at DESC, id")
SORTS = { "title" => "title", "newest" => "created_at DESC" }
Article.order(SORTS.fetch(params[:sort].to_s, "id"))
Article.order(created_at: :desc, id: :asc)

Parameters:

  • order (String, Symbol, Hash{Symbol => Symbol}, nil) —

    a Hash maps each column to :asc or :desc

Returns:

  • (self)

Raises:

  • (ArgumentError) —

    for anything else (lower(title), articles.title): use #order_sql for raw SQL



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).

Examples:

Article.order_sql("lower(title)")

Parameters:

  • sql (String)

Returns:

  • (self)


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).

Returns:



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.

Parameters:

Returns:



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.

Returns:



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).

Examples:

@articles = Article.all.to_a

Returns:



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.

Examples:

Article.where(title: ["Hello", "Bye"]).where(body: nil)
Article.where("created_at >= ?", Time.now - 86_400)
Article.where.not(body: nil)

Parameters:

  • cond (Hash{Symbol => Object}, String, nil) (defaults to: nil)
  • binds (Array) —

    one value per ? of a String condition

Returns:

  • (self)

Raises:

  • (ArgumentError) —

    for a json column, an Array bind, or a cond that is neither nil, a Hash nor a String



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.

Examples:

Article.where_between(:created_at, Time.now - 86_400, nil)

Parameters:

Returns:

  • (self)

Raises:

  • (ArgumentError) —

    when both bounds are nil, column is not a column name, or it is a json column



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.

Examples:

Article.where_like(:title, params[:q].to_s).order("title").to_a
prefix = Cybertrain::Cast.like_escape(params[:q].to_s) + "%"
Article.all.where_sql("title LIKE ? ESCAPE '\\'", [prefix])

Parameters:

  • column (Symbol, String) —

    a column name

  • text (String)

Returns:

  • (self)

Raises:

  • (ArgumentError) —

    when column is not a column name



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).

Examples:

Article.all.where_sql("created_at >= ?", [Time.now - 86_400])

Parameters:

  • sql (String)
  • binds (Array) (defaults to: []) —

    one value per ?

Returns:

  • (self)


577
# File 'docs/api/stubs/generated_app.rb', line 577

def where_sql(sql, binds = []) = (add_where_sql(sql, binds); self)