Class: Article

Inherits:
Cybertrain::Model show all
Defined in:
docs/api/stubs/generated_app.rb

Overview

What spin run gen writes into gen/models/article.rb for this table in db/schema.rb (the overview has the rules for every table):

s.create_table "articles" do |t|
  t.string "title"
  t.text "body"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

The class is named after the singular of the table (articles → Article, blog_posts → BlogPost), with one accessor per column, the finders below and an association per foreign key. app/models/article.rb reopens it, with no superclass, for validations (and validate :method), callbacks and your own methods; never edit the generated file.

Attributes. Each column has a reader and a writer (article.title, article.title = "x") holding a Ruby value of the column’s type:

Schema type Ruby value
string, text String ("" for a new record when null: false, else nil)
integer, references Integer (0 when null: false, else nil)
float Float
decimal Float, rounded to the column’s scale: when saved
boolean true / false
datetime Time (UTC), nil until set
date Date (Date.new(2026, 10, 5), stored as "2026-10-05"), nil until set; invalid or blank input stays nil, and a null: false date without a default gets a generated presence validation, so save returns false with an error on the column
json Hash with String keys ({} for a new record when null: false, else nil); its values read through Cybertrain::Cast.int, Cast.hash, Cast.array

new, update and #write_attribute cast what they are given ("42" becomes 42 for an integer column, "1"/"true"/"on" becomes true); the plain writer article.title = ... does not. A schema default: that is a plain literal becomes the initial value of a new record.

A column named like a model method or a Ruby keyword (errors, hash, class) gets a reader named <column>_column, with a note in the generated file; queries keep using the SQL name.

Encrypted columns. encrypts :body in app/models/article.rb (Cybertrain::Model.encrypts) makes the generated load_row decrypt the column (Cybertrain::Crypto.decrypt, decrypt_or_nil for a nullable one) and to_row encrypt it, so the record holds the text and the table an AES-256-GCM payload ("1:..."); ENCRYPTED_COLUMNS lists it and the relation answers encrypted_column? for it, so where, where_like, where_between, update_all and the bulk writes refuse it (ArgumentError), while pluck answers the payload. gen/app.rb then makes boot require CYBERTRAIN_ENCRYPTION_KEY (Cybertrain::Config#encryption_key); the encryption itself (cybertrain/encryptor, openssl) is in every program.

Associations come from foreign keys (t.references :article in a migration, or add_reference): the table with the key gets a belongs_to reader (Comment#article), the table it points to a has_many reader (#comments). The app/models file can declare them too, to name them or add options: has_many (dependent:), has_one and belongs_to (optional:, counter_cache:), with class_name: and foreign_key:; includes preloads them one level deep. There is no :through or polymorphic association.

Class methods (finders) collapse

COLUMN_TYPES =

Every column with its type (id included), what the bulk writes cast by: :integer, :float, :decimal, :boolean, :datetime, :date, :json, :binary, :string, :text, or :unknown.

{
  "id" => :integer,
  "title" => :string,
  "body" => :text,
  "created_at" => :datetime,
  "updated_at" => :datetime
}
DECIMAL_SCALES =

The decimal columns that declare a scale:, column => scale (none here).

Cybertrain::Model.no_decimal_scales
ENCRYPTED_COLUMNS =

The columns app/models/article.rb encrypts (encrypts :name, as ["name"]), which the bulk writes refuse as a row key and in returning:, unique_by: and update_only:, and upsert in its attrs, conflict and update (none here).

Cybertrain::Model.no_encrypted_columns

Instance Attribute Summary collapse

Attributes inherited from Cybertrain::Model

#id

Class methods (finders) collapse

Instance Method Summary collapse

Methods inherited from Cybertrain::Model

#==, after_create, after_destroy, after_save, after_update, #as_json, #attributes, before_create, before_destroy, before_save, before_update, before_validation, belongs_to, #destroy, encrypts, #errors, has_many, has_one, model_concern_insert_at, model_concern_insert_done, #new_record?, #persisted?, #reload, #save, #save!, scope, #to_json, #to_param, transaction, #update, #update_columns, #valid?, validate, validates, validates_foreign_key

Constructor Details

#initialize(attrs = {}) ⇒ Article

A new, unsaved record. Keys may be Strings or Symbols; values are cast to the column types; unknown keys and id are ignored.

Examples:

Article.new(title: "Hello")
Article.new(params.require(:article).permit(:title, :body))

Parameters:

  • attrs (Hash{String, Symbol => Object}) (defaults to: {})


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

def initialize(attrs = {}); end

Instance Attribute Details

#body ⇒ String?

The body column (t.text "body").

Returns:

  • (String, nil)


378
379
380
# File 'docs/api/stubs/generated_app.rb', line 378

def body
  @body
end

#created_at ⇒ Time?

Set by the first save when nil.

Returns:



383
384
385
# File 'docs/api/stubs/generated_app.rb', line 383

def created_at
  @created_at
end

#title ⇒ String?

The title column (t.string "title").

Returns:

  • (String, nil)


373
374
375
# File 'docs/api/stubs/generated_app.rb', line 373

def title
  @title
end

#updated_at ⇒ Time?

Set by every save.

Returns:



388
389
390
# File 'docs/api/stubs/generated_app.rb', line 388

def updated_at
  @updated_at
end

Class Method Details

.all ⇒ ArticleRelation

A relation over the whole table; every query starts here or at one of the shortcuts below. Nothing runs until rows are needed.

Examples:

@articles = Article.all.to_a

Returns:



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

def self.all = ArticleRelation.new("articles")

.column_names ⇒ Array<String>

Returns "id", then the SQL column names in schema order.

Returns:

  • (Array<String>) —

    "id", then the SQL column names in schema order



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

def self.column_names = ["id", "title", "body", "created_at", "updated_at"]

.count ⇒ Integer

Returns the number of rows in the table.

Returns:

  • (Integer) —

    the number of rows in the table



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

def self.count = all.count

.create(attrs = {}) ⇒ Article

Builds a record and saves it. Returns the record whether or not it was saved: check persisted? or errors, or use create!.

Examples:

article = Article.create(title: "Hello", body: "A body long enough")
article.persisted?  # => true

Parameters:

  • attrs (Hash{String, Symbol => Object}) (defaults to: {})

Returns:



227
228
229
230
231
# File 'docs/api/stubs/generated_app.rb', line 227

def self.create(attrs = {})
  rec = Article.new(attrs)
  rec.save
  rec
end

.create!(attrs = {}) ⇒ Article

Builds a record and saves it with save!.

Parameters:

  • attrs (Hash{String, Symbol => Object}) (defaults to: {})

Returns:

Raises:



238
239
240
241
242
# File 'docs/api/stubs/generated_app.rb', line 238

def self.create!(attrs = {})
  rec = Article.new(attrs)
  rec.save!
  rec
end

.find(id) ⇒ Article

The record with this id.

Examples:

@article = Article.find(params[:id])

Parameters:

  • id (Integer, String) —

    a String (such as params[:id]) is compared as SQLite compares it with the integer column

Returns:

Raises:



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

def self.find(id) = all.find(id)

.find_by(conditions) ⇒ Article?

The first record matching the conditions (by id), or nil.

Examples:

Article.find_by(title: "Hello")

Parameters:

  • conditions (Hash{Symbol => Object})

Returns:



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

def self.find_by(conditions) = all.find_by(conditions)

.find_by!(conditions) ⇒ Article

Returns:

Raises:

See Also:



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

def self.find_by!(conditions) = all.find_by!(conditions)

.first ⇒ Article?

Returns the record with the lowest id.

Returns:

  • (Article, nil) —

    the record with the lowest id



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

def self.first = all.first

.human_attribute_name(attr, options = {}) ⇒ String

An attribute’s name for people, as Rails’: activerecord.attributes.article.<attr> in the current locale, else the attribute humanized (:author_id → "Author"). The model’s dictionary key is its class name underscored (Admin::Post → "admin/post"). See I18n.human_attribute_name.

Examples:

# config/locales/ja.yml: ja: { activerecord: { attributes: { article: { title: "タイトル" } } } }
I18n.with_locale(:ja) { Article.human_attribute_name(:title) }  # => "タイトル"

Parameters:

  • attr (Symbol, String)
  • options (Hash) (defaults to: {}) —

    accepted for Rails’ signature; unused

Returns:

  • (String)


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

def self.human_attribute_name(attr, options = {}) = I18n.human_attribute_name("article", attr)

.includes(*names) ⇒ ArticleRelation

Examples:

@articles = Article.includes(:comments).to_a

Parameters:

  • names (Array<Symbol>) —

    association names of Article

Returns:

Raises:

  • (ArgumentError) —

    "unknown association <name> for Article"

See Also:



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

def self.includes(*names) = all.includes(*names)

.insert_all(rows, returning: [:id], record_timestamps: true) ⇒ Array<Hash{String => Object}>

Inserts many rows in multi-row statements (INSERT ... VALUES (...), (...) ON CONFLICT DO NOTHING RETURNING ...), as many rows per statement as SQLite’s bind limit allows (Cybertrain::DB::Connection#variable_limit), every statement in one transaction (joining one already open), so a failure leaves nothing of the call written; inside a transaction you opened, your rollback decides. A row that collides with an existing one on a UNIQUE index or the primary key is skipped silently.

Every row must have the same keys (Symbols or Strings, any order), or ArgumentError before anything is written; columns no row names take the table’s DEFAULT. Values take the casts a save gives them (a Time in the storage format, a Hash as JSON text, a decimal rounded to its scale, a Date as text, booleans as 1/0). created_at / updated_at, when the table has them and the rows do not, get one now for the whole call unless record_timestamps: false. No validation or callback runs.

Examples:

Article.insert_all([{ title: "One" }, { title: "Two" }]).size  # => 2
Article.insert_all(rows, returning: [:id, :title]).first  # => {"id" => 3, "title" => "One"}

Parameters:

  • rows (Array<Hash{Symbol, String => Object}>)
  • returning (Array<Symbol>, Symbol, false, nil) (defaults to: [:id]) —

    columns of the inserted rows to return, cast by type (one Symbol is one column); [], false or nil returns []; any other value raises ArgumentError

  • record_timestamps (Boolean) (defaults to: true)

Returns:

  • (Array<Hash{String => Object}>) —

    one Hash per row inserted

Raises:

  • (ArgumentError) —

    on rows with different keys, an unknown column, or an encrypted one

  • (Cybertrain::DB::Error) —

    when SQLite refuses a statement (a NOT NULL column left out); nothing is written



296
297
298
299
# File 'docs/api/stubs/generated_app.rb', line 296

def self.insert_all(rows, returning: [:id], record_timestamps: true)
  Cybertrain::Model.insert_all_into("articles", rows, COLUMN_TYPES, DECIMAL_SCALES, ENCRYPTED_COLUMNS,
                                    returning, record_timestamps, :nothing, nil, nil)
end

.insert_all!(rows, returning: [:id], record_timestamps: true) ⇒ Array<Hash{String => Object}>

insert_all without ON CONFLICT DO NOTHING: a duplicate raises, and nothing of the call is written.

Parameters:

  • rows (Array<Hash{Symbol, String => Object}>)
  • returning (Array<Symbol>, Symbol, false, nil) (defaults to: [:id]) —
  • record_timestamps (Boolean) (defaults to: true)

Returns:

  • (Array<Hash{String => Object}>) —

    one Hash per row inserted

Raises:

  • (ArgumentError) —
  • (Cybertrain::DB::Error) —

    on a duplicate or another constraint



310
311
312
313
# File 'docs/api/stubs/generated_app.rb', line 310

def self.insert_all!(rows, returning: [:id], record_timestamps: true)
  Cybertrain::Model.insert_all_into("articles", rows, COLUMN_TYPES, DECIMAL_SCALES, ENCRYPTED_COLUMNS,
                                    returning, record_timestamps, :raise, nil, nil)
end

.last ⇒ Article?

Returns the record with the highest id.

Returns:

  • (Article, nil) —

    the record with the highest id



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

def self.last = all.last

.limit(n) ⇒ ArticleRelation

Parameters:

Returns:

See Also:



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

def self.limit(n) = all.limit(n)

.order(order) ⇒ ArticleRelation

Parameters:

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

    column [ASC|DESC], comma-separated, or { column: :asc | :desc }

Returns:

See Also:



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

def self.order(order) = all.order(order)

.order_sql(sql) ⇒ ArticleRelation

Parameters:

  • sql (String) —

    raw ORDER BY text; never request data

Returns:

See Also:



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

def self.order_sql(sql) = all.order_sql(sql)

.preload(*names) ⇒ ArticleRelation

Same as includes.

Returns:



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

def self.preload(*names) = all.preload(*names)

.table_name ⇒ String

Returns the table, "articles".

Returns:

  • (String) —

    the table, "articles"



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

def self.table_name = "articles"

.upsert(attrs, conflict:, update: {}) ⇒ Integer

Cybertrain::Model.upsert for this table: one row, ON CONFLICT (conflict) DO UPDATE SET the update expressions. The values take the casts a save gives them, as the bulk writes’ do, and an encrypted column is refused among the attrs, the conflict columns and the update keys (ArgumentError).

Examples:

Article.upsert({ id: 1, title: "Hello" }, conflict: [:id], update: { title: "excluded.title" })

Parameters:

  • attrs (Hash{Symbol => Object}) —

    the row to insert

  • conflict (Array<Symbol>) —

    the conflict target’s columns

  • update (Hash{Symbol => String}) (defaults to: {}) —

    column => SQL expression

Returns:

Raises:



354
355
356
357
# File 'docs/api/stubs/generated_app.rb', line 354

def self.upsert(attrs, conflict:, update: {})
  Cybertrain::Model.upsert_into("articles", attrs, conflict, update, COLUMN_TYPES, DECIMAL_SCALES,
                                ENCRYPTED_COLUMNS)
end

.upsert_all(rows, unique_by: [:id], update_only: nil, returning: [:id], record_timestamps: true) ⇒ Array<Hash{String => Object}>

insert_all that updates a row colliding on unique_by instead of skipping it: ON CONFLICT (unique_by) DO UPDATE SET c = excluded.c for every column the rows supply except id, the unique_by columns and created_at (only those in update_only, when given), plus updated_at unless record_timestamps: false. A column the rows do not supply keeps its value. unique_by must match a UNIQUE index or the primary key.

Examples:

Article.upsert_all([{ id: 1, title: "Renamed" }])            # body unchanged
Article.upsert_all(rows, unique_by: [:title], update_only: [:body])

Parameters:

  • rows (Array<Hash{Symbol, String => Object}>)
  • unique_by (Array<Symbol>, Symbol) (defaults to: [:id]) —

    the conflict target

  • update_only (Array<Symbol>, Symbol, false, nil) (defaults to: nil) —

    the columns a conflict may update (false: none, as [])

  • returning (Array<Symbol>, Symbol, false, nil) (defaults to: [:id]) —
  • record_timestamps (Boolean) (defaults to: true)

Returns:

  • (Array<Hash{String => Object}>) —

    one Hash per row inserted or updated

Raises:

  • (ArgumentError) —

    as insert_all, or without unique_by

  • (Cybertrain::DB::Error) —

    when SQLite refuses a statement (no UNIQUE index matches unique_by)



336
337
338
339
# File 'docs/api/stubs/generated_app.rb', line 336

def self.upsert_all(rows, unique_by: [:id], update_only: nil, returning: [:id], record_timestamps: true)
  Cybertrain::Model.insert_all_into("articles", rows, COLUMN_TYPES, DECIMAL_SCALES, ENCRYPTED_COLUMNS,
                                    returning, record_timestamps, :update, unique_by, update_only)
end

.where(cond = nil, *binds) ⇒ ArticleRelation

Every query method of ArticleRelation is also a class method, written as def self.x(...) = all.x(...): where, where_like, where_between, order, order_sql, limit, offset, distinct, none, ids, find, find_by, find_by!, find_or_create_by, find_or_initialize_by, first, last, count, exists?, update_all, delete_all, destroy_all, find_each, pluck, pick, minimum_int, minimum_float, minimum_time, maximum_int, maximum_float, maximum_time, average, their _by forms, sum_int_by, sum_float_by, sum_float_sql, minimum_float_sql, maximum_float_sql, average_sql, having_sql, includes, preload, where_sql, pluck_str, pluck_int, pluck_float, count_by, count_by_sql, sum_int, sum_float and increment. Not delegated: or and not (they take or follow a relation), page, to_sql, and to_a, each, size, empty?. The ones documented here are the common ones.

Examples:

Article.where(title: "Hello").first
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) —

    values for a String condition’s ? placeholders

Returns:

See Also:



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

def self.where(cond = nil, *binds) = all.where(cond, *binds)

.where_between(column, from, to, exclude_end: false) ⇒ ArticleRelation



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

def self.where_between(column, from, to, exclude_end: false) = all.where_between(column, from, to, exclude_end: exclude_end)

.where_like(column, text) ⇒ ArticleRelation

Parameters:

  • column (Symbol, String) —

    a column name

  • text (String) —

    matched anywhere in the column, wildcards escaped

Returns:

See Also:



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

def self.where_like(column, text) = all.where_like(column, text)

Instance Method Details

#assign_attributes(attrs) ⇒ self

#write_attribute for each pair.

Parameters:

  • attrs (Hash{String, Symbol => Object})

Returns:

  • (self)


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

def assign_attributes(attrs); end

#comments ⇒ CommentRelation

has_many, from the foreign key comments.article_id (or a has_many :comments line): this article’s comments, as the comments’ Relation, so it chains like any query and runs when rows are needed. Add .to_a for an Array; templates iterate it as one. When two foreign keys of one table point here, each reader is named <table>_as_<key stem> (messages_as_sender).

When the article was loaded with Article.includes(:comments), the relation is created holding the preloaded comments: to_a, each, first, last, size and empty? answer from them without a query; count and exists? still run SQL, and a chain method (where, order, limit, …) drops them and queries as usual. reload forgets them.

Examples:

<% @article.comments.each do |comment| %>
@article.comments.where(approved: true).count
@article.comments.find(params[:id])

Returns:



433
434
435
436
437
438
# File 'docs/api/stubs/generated_app.rb', line 433

def comments
  rel = CommentRelation.new("comments").where(article_id: @id)
  return rel if @comments_preloaded.nil?

  rel.preloaded(@comments_preloaded)
end

#model_name ⇒ String

Returns "Article".

Returns:

  • (String) —

    "Article"



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

def model_name = "Article"

#read_attribute(name) ⇒ Object?

The value of a column by name, the way templates read it.

Parameters:

  • name (Symbol) —

    the SQL column name (or :id); a String gives nil

Returns:

  • (Object, nil) —

    nil for an unknown name



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

def read_attribute(name); end

#unique_value_taken?(attr, value, scope_attr, scope_value, exclude_id, case_sensitive) ⇒ Boolean

What a uniqueness: rule asks: whether another row holds value in the column attr. Every model gets it, built through the relation (the value is always a bind): where(attr => value) – LOWER(attr) = LOWER(?) when case_sensitive is false; a nil value is IS NULL either way –, narrowed by where(scope_attr => scope_value) when a scope: is given, and where.not(id: exclude_id) for a saved record, then exists?.

The model file’s if: / unless: names and validate :method lines are generated too, as validation_condition?(name) (a case calling the named method, raising ArgumentError for a name the file does not declare; every model has one) and run_custom_validations(context) (each validate method in order, under its on: / if: / unless:); a name the model file does not define stops the generator.

Examples:

Article.new.unique_value_taken?(:title, "Hello", nil, nil, 0, false)

Parameters:

  • attr (Symbol) —

    the column

  • value (Object) —

    the value to look for

  • scope_attr (Symbol, nil) —

    a column that must hold scope_value too

  • scope_value (Object)
  • exclude_id (Integer) —

    the record’s own id (0 for a new record)

  • case_sensitive (Boolean)

Returns:

  • (Boolean)

Raises:

  • (ArgumentError) —

    when attr is not a column name (case_sensitive false), or is an encrypted column (a model with encrypts checks it first; the generator already refuses uniqueness on such a column)



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

def unique_value_taken?(attr, value, scope_attr, scope_value, exclude_id, case_sensitive); end

#write_attribute(name, value) ⇒ nil

Sets a column by name, casting the value to the column’s type. Unknown names and :id are ignored.

Parameters:

  • name (Symbol)
  • value (Object)

Returns:

  • (nil)


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

def write_attribute(name, value); end